diff --git a/.agents/skills/manage-requirements/SKILL.md b/.agents/skills/manage-requirements/SKILL.md new file mode 100644 index 0000000000..e02c9500f1 --- /dev/null +++ b/.agents/skills/manage-requirements/SKILL.md @@ -0,0 +1,134 @@ +--- +name: manage-requirements +description: >- + Author and validate FR/NFR requirement catalogs (MD + YAML) for any TCE + project. Use when creating, migrating, editing, or validating requirements, + specs with acceptance criteria, requirements.yaml, FR-/NFR- IDs, or + component/screen/script requirement catalogs. +--- + +# Manage requirements + +Cross-project skill. Schemas live here and apply to CollegeV2, Military, High School, Shared, or any new module. + +## File contract + +Each feature is a folder with exactly two artifacts: + +| File | Role | +| --- | --- | +| `.md` (or `README.md`) | Human/AI narrative: purpose, actors, config, links | +| `requirements.yaml` | Machine-checked catalog (`requirements[]`) | + +Schemas (source of truth): + +- [schemas/requirement.schema.json](schemas/requirement.schema.json) — single Requirement +- [schemas/requirements-catalog.schema.json](schemas/requirements-catalog.schema.json) — catalog document + +Templates: [templates/](templates/). + +## Catalog shape + +```yaml +specId: my-feature +kind: component # component | screen | script +title: My feature +config: {} # props / ports / section ids — keep FRs reusable +dependsOn: [] # other specId values +requirements: + - id: FR-001 + requirementType: Functional + title: ... + statement: ... + priority: High + status: Draft + acceptanceCriteria: + - given: ... + when: ... + then: ... +``` + +Rules: + +- Local IDs `FR-NNN` / `NFR-NNN` unique **within** one catalog +- Cross-feature refs: `specId#FR-001` in `dependencies` +- Functional → `acceptanceCriteria` required +- NonFunctional → `category`, `metrics`, `verificationMethod` required +- Edge-case scenario IDs (e.g. `CE-001`) go in `traceability.testCases` only + +## Authoring by kind + +1. **component** — Behavior given `config`. No screen names in `statement` / `acceptanceCriteria`. Screens list the component in `dependsOn` and describe their config in the MD. +2. **script** — Domain outcomes via named ports. No vendor URLs or ProcessMaker HTTP in statements; adapters belong in `config` / `assumptions`. +3. **screen** — Workflow composition, permissions, Continue rules. Reuse components via `dependsOn`; do not duplicate component FRs. + +### CollegeV2 course comments (`comments_log`) + +- Prefer a **component** catalog for shared `CommentsLogTable` (read-only thread); screen RFs `dependsOn` it and describe when the section is visible (`comments_log.length > 0`). +- In screen MD **assumptions**, state whether comments are stored in **case JSON** (`course.comments_log[]`), appended only on **save** from a draft field (`comments_note` / student `comments`), and/or loaded later via **`acol_applicant_course_comments`** HTTP — avoid contradictory `then` clauses across catalogs. +- Acceptance criteria should spell out **role** (`tco`, `student`), **read vs write**, and **append-on-save** (draft is not in the log until save succeeds). +- Multi-external articulation: if one save updates linked courses, say whether companions receive the same `comments_log` entries or only articulation/inbox fields. + +Suggested project layout (optional; any tree of `requirements.yaml` validates): + +```text +ai-docs//requirements/ + components//{.md,requirements.yaml} + screens//{.md,requirements.yaml} + scripts//{.md,requirements.yaml} +``` + +## Validate + +Primary gate (schema + heuristic quality): + +```bash +npm run check:requirements # all ai-docs/*/requirements +npm run check:requirements -- college-v2 # one project +npm run check:requirements -- military +``` + +Schema-only (path optional; default is every `ai-docs/*/requirements` tree): + +```bash +npm run validate:requirements +npm run validate:requirements -- path/to/requirements.yaml +npm run validate:requirements -- path/to/feature-or-tree +``` + +Schema checks required fields, unique IDs, `dependsOn`, companion markdown (`.md` or `README.md`), and non-empty Given/When/Then. Tautological acceptance criteria (placeholder given/when, or `then` repeating the title) are warnings, not hard failures. + +Quality harness (any project) lives in [quality/](quality/). Project text fixtures stay under `ai-docs//quality/` (`*.yaml` questions, optional `vocabulary.md`). `check:requirements` / `judge_catalog.py` exits non-zero while any FR fails (for example stub acceptance criteria). + +Harness unit tests (tooling, not catalog gates): + +```bash +npm run test:requirements-schema +npm run test:requirements-quality +``` + +Laya (downloads a local checkpoint): + +```bash +# pip install -r .agents/skills/manage-requirements/quality/requirements.txt +# REQUIREMENTS_PROJECT=college-v2 LAYA_SOURCE=laya .agents/skills/manage-requirements/quality/run_laya_eval.sh +``` + +Global tests are `ai-docs//quality/*.yaml` with `applies.all`. Domain extras are more YAML in that folder with `applies.ids` (or kinds/tags). + +Checklist before finishing: + +- [ ] MD + `requirements.yaml` pair exists +- [ ] `npm run check:requirements -- ` passes (or `validate:requirements -- ` for schema-only) +- [ ] IDs unique in catalog; Functional/NonFunctional fields complete +- [ ] Component/script statements stay screen-/vendor-agnostic +- [ ] Screen catalogs `dependsOn` shared components instead of copying FRs +- [ ] Edge cases linked via `traceability.testCases` when known + +## Create / migrate workflow + +1. Choose `kind` and `specId` (stable folder basename). +2. Copy templates from `templates/`; rename the MD to match `specId`. +3. Extract FRs from existing design docs / edge cases; map scenarios to acceptance criteria and `testCases`. +4. For screens that embed a reusable UI, create/reuse a **component** catalog first, then `dependsOn` it. +5. Validate; fix schema errors before committing. diff --git a/.agents/skills/manage-requirements/quality/README.md b/.agents/skills/manage-requirements/quality/README.md new file mode 100644 index 0000000000..413ab2b3d0 --- /dev/null +++ b/.agents/skills/manage-requirements/quality/README.md @@ -0,0 +1,30 @@ +# Requirement quality harness + +Cross-project Python tools for FR/NFR quality (schema companion to `scripts/validate-requirements.js`). + +Project-specific text stays under `ai-docs//quality/`: + +| Path | Role | +| --- | --- | +| `*.yaml` | Global QC (`applies.all`) and targeted extras | +| `vocabulary.md` | Optional domain terms prepended to each Laya state | + +```bash +# Heuristic gate (any project) +python3 judge_catalog.py --project college-v2 --source heuristic + +# Or explicit paths +python3 judge_catalog.py \ + --root ai-docs/military/requirements \ + --questions ai-docs/military/quality \ + --source heuristic + +# Unit tests: synthetic catalogs + global QC from ai-docs//quality +# Discovers every pack with quality/*.yaml, or pin one: +# REQUIREMENTS_PROJECT=military python3 -m unittest discover -s . -p 'test_*.py' +python3 -m unittest discover -s . -p 'test_*.py' + +# Laya (optional) +pip install -r requirements.txt +REQUIREMENTS_PROJECT=college-v2 LAYA_SOURCE=laya ./run_laya_eval.sh +``` diff --git a/.agents/skills/manage-requirements/quality/build_gold.py b/.agents/skills/manage-requirements/quality/build_gold.py new file mode 100644 index 0000000000..2c77743ecf --- /dev/null +++ b/.agents/skills/manage-requirements/quality/build_gold.py @@ -0,0 +1,65 @@ +"""Generate targeted-extra JSONL from catalogs + question YAML (optional Laya input).""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from extract_requirement_states import iter_requirement_rows, to_jsonl_record +from load_questions import ( + global_laya_questions, + load_question_documents, + targeted_expected_by_requirement, + targeted_laya_by_requirement, + validate_questions, +) +from project import add_project_args, load_vocabulary, paths_from_args + + +def write_jsonl(path: Path, records: list[dict]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("w", encoding="utf-8") as handle: + for record in records: + handle.write(json.dumps(record, ensure_ascii=False) + "\n") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser() + add_project_args(parser) + parser.add_argument("--extra-out", type=Path, help="Default: /extra.jsonl") + args = parser.parse_args(argv) + + paths = paths_from_args(args) + extra_out = args.extra_out or (paths.questions_dir / "extra.jsonl") + + questions = load_question_documents(paths.questions_dir) + quality_questions = global_laya_questions(questions) + vocabulary = load_vocabulary(paths.vocabulary_path) + rows = iter_requirement_rows( + paths.requirements_root, + vocabulary=vocabulary, + questions=quality_questions, + ) + errors = validate_questions(rows, paths.questions_dir) + if errors: + for err in errors: + print(f"FAIL {err}") + return 1 + + rows_by_id = {row["id"]: row for row in rows} + extra_questions = targeted_laya_by_requirement(rows, questions) + extra_expected = targeted_expected_by_requirement(rows, questions) + extra_records = [ + to_jsonl_record(rows_by_id[key], extra_expected[key], questions=extra_questions[key]) + for key in extra_questions + if key in extra_expected + ] + + write_jsonl(extra_out, extra_records) + print(f"Wrote {len(extra_records)} extra-question rows to {extra_out}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.agents/skills/manage-requirements/quality/extract_requirement_states.py b/.agents/skills/manage-requirements/quality/extract_requirement_states.py new file mode 100644 index 0000000000..80fd8c8214 --- /dev/null +++ b/.agents/skills/manage-requirements/quality/extract_requirement_states.py @@ -0,0 +1,199 @@ +"""Walk requirements.yaml catalogs and emit one Laya state per requirement.""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +import yaml + +from project import REPO_ROOT, add_project_args, load_vocabulary, paths_from_args + +PLACEHOLDER_GIVEN = "the feature is available" +PLACEHOLDER_WHEN = "the behavior is exercised" + + +def collect_yaml_files(root: Path) -> list[Path]: + if root.is_file(): + return [root] + return sorted(root.rglob("requirements.yaml")) + + +def _normalize(value: object) -> str: + return " ".join(str(value or "").lower().split()) + + +def is_stub_criterion(req: dict, criterion: dict) -> bool: + given = str(criterion.get("given") or "") + when = str(criterion.get("when") or "") + then = _normalize(criterion.get("then")) + title = _normalize(req.get("title")) + placeholder = PLACEHOLDER_GIVEN in given.lower() and PLACEHOLDER_WHEN in when.lower() + then_repeats_title = bool(then) and then == title + return placeholder or then_repeats_title + + +def requirement_has_stub_ac(req: dict) -> bool: + criteria = req.get("acceptanceCriteria") or [] + return any(is_stub_criterion(req, item) for item in criteria if isinstance(item, dict)) + + +# Backward-compatible aliases. +is_tautological_criterion = is_stub_criterion +requirement_is_tautological = requirement_has_stub_ac + + +def compact_requirement(req: dict) -> dict: + payload = { + "id": req.get("id"), + "requirementType": req.get("requirementType"), + "title": req.get("title"), + "statement": req.get("statement"), + "priority": req.get("priority"), + "status": req.get("status"), + } + if req.get("acceptanceCriteria"): + payload["acceptanceCriteria"] = req["acceptanceCriteria"] + if req.get("metrics"): + payload["metrics"] = req["metrics"] + if req.get("verificationMethod"): + payload["verificationMethod"] = req["verificationMethod"] + if req.get("category"): + payload["category"] = req["category"] + return payload + + +def build_state(catalog: dict, req: dict, vocabulary: str = "") -> str: + body = yaml.safe_dump(compact_requirement(req), sort_keys=False, allow_unicode=True).strip() + parts = [] + if vocabulary.strip(): + parts.append(vocabulary.strip()) + parts.append("") + parts.extend( + [ + "Requirement catalog:", + f"specId: {catalog.get('specId')}", + f"kind: {catalog.get('kind')}", + f"title: {catalog.get('title')}", + "", + body, + "", + ] + ) + return "\n".join(parts) + + +def requirement_key(spec_id: str, req_id: str) -> str: + return f"{spec_id}#{req_id}" + + +def relative_repo_path(path: Path, repo_root: Path | None = None) -> str: + root = repo_root or REPO_ROOT + resolved = path.resolve() + try: + return resolved.relative_to(root.resolve()).as_posix() + except ValueError: + return resolved.as_posix() + + +def requirement_line_numbers(text: str) -> dict[str, int]: + """Map requirement id -> 1-based line of the `- id:` entry.""" + lines: dict[str, int] = {} + for index, line in enumerate(text.splitlines(), start=1): + stripped = line.strip() + if not stripped.startswith("- id:"): + continue + req_id = stripped.split(":", 1)[1].strip().strip("\"'") + if req_id and req_id not in lines: + lines[req_id] = index + return lines + + +def iter_requirement_rows( + root: Path, + *, + vocabulary: str = "", + questions: dict | None = None, + repo_root: Path | None = None, +) -> list[dict]: + rows = [] + for yaml_path in collect_yaml_files(root): + text = yaml_path.read_text(encoding="utf-8") + catalog = yaml.safe_load(text) + if not isinstance(catalog, dict): + continue + spec_id = catalog.get("specId") + line_by_id = requirement_line_numbers(text) + source_path = relative_repo_path(yaml_path, repo_root=repo_root) + for req in catalog.get("requirements") or []: + if not isinstance(req, dict) or not req.get("id"): + continue + req_id = str(req["id"]) + key = requirement_key(str(spec_id), req_id) + tags = req.get("tags") or [] + if not isinstance(tags, list): + tags = [tags] + rows.append( + { + "id": key, + "specId": spec_id, + "requirementId": req_id, + "title": str(req.get("title") or "").strip(), + "sourcePath": source_path, + "sourceLine": line_by_id.get(req_id), + "requirementType": req.get("requirementType"), + "kind": catalog.get("kind"), + "reqTags": [str(tag) for tag in tags], + "stub_ac": requirement_has_stub_ac(req), + "tautological": requirement_has_stub_ac(req), + "state": build_state(catalog, req, vocabulary=vocabulary), + "questions": questions if questions is not None else {}, + "tags": [str(catalog.get("kind") or "unknown"), str(spec_id)], + "language": "en", + "model": "english", + } + ) + return rows + + +def to_jsonl_record(row: dict, expected: dict | None = None, questions: dict | None = None) -> dict: + record = { + "state": row["state"], + "questions": questions if questions is not None else row["questions"], + "tags": row["tags"] + ([row["id"]]), + "language": row["language"], + "model": row["model"], + } + if expected is not None: + record["expected"] = expected + return record + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Extract requirements as Laya states.") + add_project_args(parser) + parser.add_argument("--jsonl", type=Path, help="Write one JSON object per requirement") + args = parser.parse_args(argv) + + paths = paths_from_args(args) + vocabulary = load_vocabulary(paths.vocabulary_path) + rows = iter_requirement_rows(paths.requirements_root, vocabulary=vocabulary) + if args.jsonl: + args.jsonl.parent.mkdir(parents=True, exist_ok=True) + with args.jsonl.open("w", encoding="utf-8") as handle: + for row in rows: + handle.write(json.dumps(to_jsonl_record(row), ensure_ascii=False) + "\n") + else: + json.dump( + [{"id": row["id"], "stub_ac": row["stub_ac"]} for row in rows], + sys.stdout, + indent=2, + ) + sys.stdout.write("\n") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.agents/skills/manage-requirements/quality/judge_catalog.py b/.agents/skills/manage-requirements/quality/judge_catalog.py new file mode 100644 index 0000000000..11d615e874 --- /dev/null +++ b/.agents/skills/manage-requirements/quality/judge_catalog.py @@ -0,0 +1,347 @@ +"""Judge requirements and fail when any global QC check fails.""" + +from __future__ import annotations + +import argparse +import json +import os +import sys +from pathlib import Path + +from extract_requirement_states import iter_requirement_rows +from load_questions import ( + defect_criteria_from_questions, + global_laya_questions, + load_question_documents, + noul_question_ids, +) +from project import add_project_args, load_vocabulary, paths_from_args + +NOUL_FAIL_THRESHOLD = 0.5 +MAX_LOW_CONFIDENCE = 0 +_ANSI_RED = "\033[31m" +_ANSI_RESET = "\033[0m" + +DEFECT_LABELS = { + "stub_ac": "stub acceptance criteria", + "vague_then": "vague then/metric", + "vocab_drift": "vocabulary drift", + "missing_observable": "missing observable outcome", + "unbounded": "unbounded / TBD scope", +} + + +def heuristic_answers(row: dict) -> dict: + stub_ac = bool(row.get("stub_ac") if "stub_ac" in row else row.get("tautological")) + yes = 0.95 + no = 0.05 + return { + "clear": {"noul": yes, "answer_confidence": yes, "low_confidence": False}, + "verifiable": { + "noul": no if stub_ac else yes, + "answer_confidence": yes, + "low_confidence": False, + }, + "testable": { + "noul": no if stub_ac else yes, + "answer_confidence": yes, + "low_confidence": False, + }, + "consistent": {"noul": yes, "answer_confidence": yes, "low_confidence": False}, + "achievable": {"noul": yes, "answer_confidence": yes, "low_confidence": False}, + "primary_defect": { + "choice": "stub_ac" if stub_ac else "none", + "answer_confidence": yes, + "low_confidence": False, + }, + } + + +def noul_value(answer: dict) -> float: + if "noul" in answer and isinstance(answer["noul"], (int, float)): + return float(answer["noul"]) + choice = str(answer.get("choice") or "").upper() + if choice == "A": + return 1.0 + if choice == "B": + return 0.0 + return 0.0 + + +def failed_quality_reasons( + answers: dict, + noul_ids: tuple[str, ...], + min_confidence: float = 0.45, +) -> list[str]: + """Return every failed global QC question id (and low_confidence when gated).""" + reasons = [] + for key in noul_ids: + answer = answers.get(key) or {} + confidence = float(answer.get("answer_confidence") or noul_value(answer) or 0.0) + if answer.get("low_confidence") or confidence < min_confidence: + reasons.append("low_confidence") + continue + if noul_value(answer) < NOUL_FAIL_THRESHOLD: + reasons.append(key) + seen = set() + ordered = [] + for reason in reasons: + if reason not in seen: + seen.add(reason) + ordered.append(reason) + return ordered + + +def requirement_quality_failure( + answers: dict, + noul_ids: tuple[str, ...], + min_confidence: float = 0.45, +) -> tuple[bool, str | None]: + reasons = failed_quality_reasons(answers, noul_ids, min_confidence) + if not reasons: + return False, None + return True, reasons[0] + + +def primary_defect_of(answers: dict) -> str | None: + defect = answers.get("primary_defect") or {} + choice = defect.get("choice") + return str(choice) if choice else None + + +def defect_label(primary_defect: str | None) -> str | None: + if not primary_defect or primary_defect == "none": + return None + return DEFECT_LABELS.get(primary_defect, primary_defect.replace("_", " ")) + + +def failure_reason_text(primary_defect: str | None) -> str: + return defect_label(primary_defect) or "quality check failed" + + +def use_color(stream=None) -> bool: + force = (os.environ.get("FORCE_COLOR") or "").strip().lower() + if force in {"1", "true", "yes", "on"}: + return True + if force in {"0", "false", "no", "off"}: + return False + if os.environ.get("NO_COLOR"): + return False + target = stream if stream is not None else sys.stdout + return bool(getattr(target, "isatty", lambda: False)()) + + +def failed_badge(color: bool | None = None) -> str: + if color is None: + color = use_color() + if color: + return f"{_ANSI_RED}[FAILED]{_ANSI_RESET}" + return "[FAILED]" + + +def format_failure_heading(item: dict, *, color: bool | None = None) -> str: + """Build: path#line FR-ID: Title [FAILED] (falls back to catalog#id).""" + source_path = item.get("sourcePath") + source_line = item.get("sourceLine") + req_id = item.get("requirementId") or ( + str(item.get("id") or "").split("#", 1)[-1] if item.get("id") else "UNKNOWN" + ) + title = str(item.get("title") or "").strip() + if source_path and source_line: + location = f"{source_path}#{source_line}" + elif source_path: + location = str(source_path) + else: + location = str(item.get("id") or req_id) + badge = failed_badge(color) + if title: + return f"✖ {location} {req_id}: {title} {badge}" + return f"✖ {location} {req_id} {badge}" + + +def format_failure_detail( + item: dict | str, + reasons: list[str] | None = None, + primary_defect: str | None = None, + *, + color: bool | None = None, + **kwargs, +) -> list[str]: + if isinstance(item, str): + item = { + "id": item, + "reasons": reasons or [], + "primary_defect": primary_defect or kwargs.get("primary_defect"), + } + else: + reasons = reasons if reasons is not None else item.get("reasons") or [] + if primary_defect is None: + primary_defect = item.get("primary_defect") + checks = ", ".join(reasons or []) if reasons else "unknown" + return [ + format_failure_heading(item, color=color), + f"Failed checks: [{checks}]", + f"Reason: {failure_reason_text(primary_defect)}", + ] + + +def snapshot_from_rows( + rows: list[dict], + answers_by_id: dict[str, dict], + source: str, + noul_ids: tuple[str, ...], +) -> dict: + failures = [] + low_confidence = 0 + for row in rows: + answers = answers_by_id[row["id"]] + reasons = failed_quality_reasons(answers, noul_ids) + if "low_confidence" in reasons: + low_confidence += 1 + if reasons: + failures.append( + { + "id": row["id"], + "requirementId": row.get("requirementId"), + "title": row.get("title") or "", + "sourcePath": row.get("sourcePath"), + "sourceLine": row.get("sourceLine"), + "reasons": reasons, + "primary_defect": primary_defect_of(answers), + } + ) + failures.sort(key=lambda item: item["id"]) + return { + "source": source, + "failedIds": [item["id"] for item in failures], + "failures": failures, + "lowConfidenceCount": low_confidence, + "requirementCount": len(rows), + } + + +RULE = "─" * 60 + + +def format_summary(current: dict) -> list[str]: + total = int(current.get("requirementCount") or 0) + failed = len(current.get("failures") or []) + warnings = int(current.get("lowConfidenceCount") or 0) + passed = max(total - failed, 0) + return [ + RULE, + f"Requirements analyzed: {total}", + f"Passed: {passed}", + f"Failed: {failed}", + f"Warnings: {warnings}", + RULE, + ] + + +def format_quality_report( + current: dict, + defect_info: dict[str, str] | None = None, + *, + color: bool | None = None, +) -> list[str]: + """Human-readable report lines for quality failures (empty when clean).""" + failures = list(current.get("failures") or []) + if not failures and current.get("lowConfidenceCount", 0) <= MAX_LOW_CONFIDENCE: + return [] + + lines = format_summary(current) + lines.append("") + for index, item in enumerate(failures): + if index: + lines.append("") + lines.extend(format_failure_detail(item, defect_info=defect_info, color=color)) + lines.append("") + return lines + + +def report_quality_failures( + current: dict, + defect_info: dict[str, str] | None = None, + *, + color: bool | None = None, +) -> list[str]: + """Return error lines when the catalog has quality failures.""" + return format_quality_report(current, defect_info=defect_info, color=color) + + +def compare_snapshot(current: dict, committed: dict | None = None, **_kwargs) -> list[str]: + del committed + return report_quality_failures(current) + + +def predict_with_laya(rows: list[dict], min_confidence: float) -> dict[str, dict]: + from laya import Router + + router = Router() + answers_by_id = {} + for row in rows: + result = router.predict( + row["state"], + row["questions"], + model="english", + min_confidence=min_confidence, + ) + answers_by_id[row["id"]] = result["answers"] + return answers_by_id + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser( + description="Judge requirement quality; fails if any FR fails global QC." + ) + add_project_args(parser) + parser.add_argument("--source", choices=("heuristic", "laya"), default="heuristic") + parser.add_argument("--min-confidence", type=float, default=0.45) + parser.add_argument("--report-only", action="store_true") + parser.add_argument("--report", type=Path) + args = parser.parse_args(argv) + + paths = paths_from_args(args) + questions = load_question_documents(paths.questions_dir) + quality_questions = global_laya_questions(questions) + noul_ids = noul_question_ids(questions) + defect_info = defect_criteria_from_questions(questions) + vocabulary = load_vocabulary(paths.vocabulary_path) + rows = iter_requirement_rows( + paths.requirements_root, + vocabulary=vocabulary, + questions=quality_questions, + ) + + if args.source == "laya": + answers_by_id = predict_with_laya(rows, args.min_confidence) + source = "laya" + else: + answers_by_id = {row["id"]: heuristic_answers(row) for row in rows} + source = "heuristic" + + current = snapshot_from_rows(rows, answers_by_id, source, noul_ids) + if args.report: + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(json.dumps(current, indent=2) + "\n", encoding="utf-8") + + report = report_quality_failures(current, defect_info=defect_info) + if args.report_only: + for line in report or format_summary(current): + print(line) + return 0 + + if report: + for line in report: + print(line) + return 1 + + for line in format_summary(current): + print(line) + print("") + print("All requirements passed global QC.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.agents/skills/manage-requirements/quality/judge_extra.py b/.agents/skills/manage-requirements/quality/judge_extra.py new file mode 100644 index 0000000000..b90fe5cd9e --- /dev/null +++ b/.agents/skills/manage-requirements/quality/judge_extra.py @@ -0,0 +1,98 @@ +"""Run targeted Laya questions (applies.ids / kinds / tags, not global QC).""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from extract_requirement_states import iter_requirement_rows +from load_questions import ( + global_laya_questions, + load_question_documents, + targeted_expected_by_requirement, + targeted_laya_by_requirement, + validate_questions, +) +from project import add_project_args, load_vocabulary, paths_from_args + + +def _matches(expected, answer: dict) -> bool: + if "noul" in answer and isinstance(expected, bool): + return (float(answer["noul"]) >= 0.5) is expected + if "choice" in answer: + return answer["choice"] == expected + if "score" in answer and isinstance(expected, (int, float)): + return int(round(float(answer["score"]))) == int(expected) + return False + + +def judge_extra_answers( + answers_by_id: dict[str, dict], + expected_by_id: dict[str, dict], + reserved_ids: set[str] | None = None, +) -> list[str]: + errors = [] + reserved = reserved_ids or set() + for row_id, expected in expected_by_id.items(): + answers = answers_by_id.get(row_id) or {} + for qid, value in expected.items(): + if qid in reserved: + errors.append(f"{row_id}: extra id {qid} collides with global QC") + continue + if not _matches(value, answers.get(qid) or {}): + errors.append(f"{row_id} extra.{qid}: expected {value!r}, got {answers.get(qid)!r}") + return errors + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Judge targeted per-requirement Laya questions.") + add_project_args(parser) + parser.add_argument("--report", type=Path) + args = parser.parse_args(argv) + + paths = paths_from_args(args) + questions = load_question_documents(paths.questions_dir) + quality_questions = global_laya_questions(questions) + vocabulary = load_vocabulary(paths.vocabulary_path) + rows = iter_requirement_rows( + paths.requirements_root, + vocabulary=vocabulary, + questions=quality_questions, + ) + errors = validate_questions(rows, paths.questions_dir) + if errors: + for err in errors: + print(f"FAIL {err}") + return 1 + + extra_questions = targeted_laya_by_requirement(rows, questions) + extra_expected = targeted_expected_by_requirement(rows, questions) + if not extra_questions: + print("No targeted Laya questions.") + return 0 + + from laya import Router + + rows_by_id = {row["id"]: row for row in rows} + router = Router() + answers_by_id = {} + for row_id, qset in extra_questions.items(): + result = router.predict(rows_by_id[row_id]["state"], qset, model="english") + answers_by_id[row_id] = result["answers"] + + if args.report: + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(json.dumps(answers_by_id, indent=2, default=str) + "\n", encoding="utf-8") + + mismatches = judge_extra_answers(answers_by_id, extra_expected, set(quality_questions)) + if mismatches: + for err in mismatches: + print(f"FAIL {err}") + return 1 + print(f"{len(extra_questions)} targeted Laya requirement(s) matched expected labels.") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.agents/skills/manage-requirements/quality/load_questions.py b/.agents/skills/manage-requirements/quality/load_questions.py new file mode 100644 index 0000000000..07fc709c57 --- /dev/null +++ b/.agents/skills/manage-requirements/quality/load_questions.py @@ -0,0 +1,234 @@ +"""Load quality-question YAML tests (global QC and targeted extras).""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +import yaml + +from extract_requirement_states import iter_requirement_rows +from project import add_project_args, load_vocabulary, paths_from_args + +LAYA_TYPES = {"noul", "choice", "score"} +CHECK_TYPE = "check" +METADATA_KEYS = {"id", "applies", "exclude", "expected", "checks", "path"} + + +def _as_list(value) -> list: + if value is None: + return [] + if isinstance(value, list): + return value + return [value] + + +def load_question_documents(questions_dir: Path) -> list[dict]: + if not questions_dir.is_dir(): + raise FileNotFoundError(f"Questions directory not found: {questions_dir}") + documents = [] + for path in sorted(questions_dir.glob("*.yaml")): + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + if not isinstance(data, dict): + raise ValueError(f"{path} must be a YAML mapping") + qid = data.get("id") + if qid != path.stem: + raise ValueError(f"{path.name}: id {qid!r} must match filename stem {path.stem!r}") + qtype = data.get("type") + if qtype not in LAYA_TYPES | {CHECK_TYPE}: + raise ValueError(f"{path.name}: type must be noul, choice, score, or check") + data = dict(data) + data["path"] = path + documents.append(data) + if not documents: + raise ValueError(f"No question YAML files in {questions_dir}") + return documents + + +def is_global_qc(question: dict) -> bool: + applies = question.get("applies") or {} + return bool(applies.get("all")) and question.get("type") in LAYA_TYPES + + +def laya_payload(question: dict) -> dict: + payload = {} + for key, value in question.items(): + if key not in METADATA_KEYS: + payload[key] = value + return payload + + +def global_laya_questions(questions: list[dict]) -> dict: + return {q["id"]: laya_payload(q) for q in questions if is_global_qc(q)} + + +def noul_question_ids(questions: list[dict]) -> tuple[str, ...]: + return tuple(q["id"] for q in questions if is_global_qc(q) and q.get("type") == "noul") + + +def quality_expected_keys(questions: list[dict]) -> tuple[str, ...]: + return tuple(q["id"] for q in questions if is_global_qc(q)) + + +def question_applies(question: dict, row: dict) -> bool: + exclude = question.get("exclude") or {} + if row["id"] in _as_list(exclude.get("ids")): + return False + if row.get("specId") in _as_list(exclude.get("specIds")): + return False + applies = question.get("applies") or {} + if applies.get("all"): + return True + filters = False + if applies.get("ids"): + filters = True + if row["id"] not in _as_list(applies.get("ids")): + return False + if applies.get("specIds"): + filters = True + if row.get("specId") not in _as_list(applies.get("specIds")): + return False + if applies.get("kinds"): + filters = True + if row.get("kind") not in _as_list(applies.get("kinds")): + return False + if applies.get("requirementTypes"): + filters = True + if row.get("requirementType") not in _as_list(applies.get("requirementTypes")): + return False + if applies.get("tags"): + filters = True + row_tags = {str(tag) for tag in (row.get("reqTags") or [])} + if not row_tags.intersection({str(tag) for tag in _as_list(applies.get("tags"))}): + return False + return filters + + +def expected_for(question: dict, row_id: str): + expected = question.get("expected") + if isinstance(expected, dict): + return expected.get(row_id) + return expected + + +def targeted_laya_by_requirement(rows: list[dict], questions: list[dict]) -> dict[str, dict]: + by_id: dict[str, dict] = {} + for question in questions: + if question.get("type") not in LAYA_TYPES or is_global_qc(question): + continue + for row in rows: + if not question_applies(question, row): + continue + by_id.setdefault(row["id"], {})[question["id"]] = laya_payload(question) + return by_id + + +def targeted_expected_by_requirement(rows: list[dict], questions: list[dict]) -> dict[str, dict]: + by_id: dict[str, dict] = {} + for question in questions: + if question.get("type") not in LAYA_TYPES or is_global_qc(question): + continue + for row in rows: + if not question_applies(question, row): + continue + value = expected_for(question, row["id"]) + if value is None: + continue + by_id.setdefault(row["id"], {})[question["id"]] = value + return by_id + + +def defect_criteria_from_questions(questions: list[dict]) -> dict[str, str]: + for question in questions: + if question["id"] == "primary_defect": + criteria = question.get("criteria") or {} + return {str(key): str(value) for key, value in criteria.items() if key != "none"} + return {} + + +def _haystack(row: dict, check: dict) -> str: + target = check.get("in", "state") + if target == "state": + return row["state"] + raise ValueError(f"Unsupported check.in {target!r}") + + +def run_question_checks(row: dict, question: dict) -> list[str]: + errors = [] + for index, check in enumerate(question.get("checks") or []): + if not isinstance(check, dict) or "text" not in check: + errors.append(f"{question['id']}@{row['id']} checks[{index}]: needs type and text") + continue + kind = check.get("type") + needle = str(check["text"]) + found = needle.lower() in _haystack(row, check).lower() + if kind == "contains" and not found: + errors.append(f"{question['id']}@{row['id']} checks[{index}]: expected to contain {needle!r}") + elif kind == "notContains" and found: + errors.append(f"{question['id']}@{row['id']} checks[{index}]: must not contain {needle!r}") + elif kind not in {"contains", "notContains"}: + errors.append(f"{question['id']}@{row['id']} checks[{index}]: unknown type {kind!r}") + return errors + + +def validate_questions(rows: list[dict], questions_dir: Path) -> list[str]: + questions = load_question_documents(questions_dir) + errors: list[str] = [] + global_ids = [q["id"] for q in questions if is_global_qc(q)] + if not global_ids: + errors.append("no global QC questions (applies.all + noul/choice/score)") + seen = set() + rows_by_id = {row["id"]: row for row in rows} + for question in questions: + qid = question["id"] + if qid in seen: + errors.append(f"duplicate question id {qid}") + seen.add(qid) + applies = question.get("applies") or {} + if not applies.get("all") and not any( + applies.get(key) for key in ("ids", "specIds", "kinds", "requirementTypes", "tags") + ): + errors.append(f"{qid}: applies must set all: true or at least one selector") + for key in ("ids", "specIds"): + for ref in _as_list((applies.get(key) or []) + _as_list((question.get("exclude") or {}).get(key))): + if key == "ids" and ref not in rows_by_id: + errors.append(f"{qid}: applies/exclude id {ref} not found in catalogs") + if question.get("type") == CHECK_TYPE and not question.get("checks"): + errors.append(f"{qid}: check questions need checks[]") + if question.get("type") in LAYA_TYPES and not is_global_qc(question): + targets = [row for row in rows if question_applies(question, row)] + if not targets: + errors.append(f"{qid}: targeted Laya question matches no requirements") + for row in targets: + if expected_for(question, row["id"]) is None: + errors.append(f"{qid}: missing expected for {row['id']}") + for row in rows: + if question_applies(question, row) and question.get("checks"): + errors.extend(run_question_checks(row, question)) + return errors + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Validate quality question YAML against catalogs.") + add_project_args(parser) + args = parser.parse_args(argv) + paths = paths_from_args(args) + vocabulary = load_vocabulary(paths.vocabulary_path) + rows = iter_requirement_rows(paths.requirements_root, vocabulary=vocabulary) + errors = validate_questions(rows, paths.questions_dir) + if errors: + for err in errors: + print(f"FAIL {err}") + return 1 + questions = load_question_documents(paths.questions_dir) + targeted = sum(1 for q in questions if q.get("type") in LAYA_TYPES and not is_global_qc(q)) + checks = sum(1 for q in questions if q.get("type") == CHECK_TYPE) + print( + f"{len(global_laya_questions(questions))} global QC questions, " + f"{targeted} targeted Laya question(s), {checks} check question(s)." + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.agents/skills/manage-requirements/quality/project.py b/.agents/skills/manage-requirements/quality/project.py new file mode 100644 index 0000000000..77ca6381ee --- /dev/null +++ b/.agents/skills/manage-requirements/quality/project.py @@ -0,0 +1,142 @@ +"""Resolve per-project requirements + quality-question paths under ai-docs/.""" + +from __future__ import annotations + +import argparse +import os +from dataclasses import dataclass +from pathlib import Path + +QUALITY_PKG = Path(__file__).resolve().parent +# quality/ -> manage-requirements/ -> skills/ -> .agents/ -> +REPO_ROOT = QUALITY_PKG.parents[3] + + +@dataclass(frozen=True) +class ProjectPaths: + name: str | None + requirements_root: Path + questions_dir: Path + vocabulary_path: Path + + +def resolve_project(name: str, repo_root: Path | None = None) -> ProjectPaths: + root = repo_root or REPO_ROOT + questions_dir = root / "ai-docs" / name / "quality" + return ProjectPaths( + name=name, + requirements_root=root / "ai-docs" / name / "requirements", + questions_dir=questions_dir, + vocabulary_path=questions_dir / "vocabulary.md", + ) + + +def discover_quality_projects(repo_root: Path | None = None) -> list[str]: + """Return ai-docs/ folders that contain quality/*.yaml.""" + docs = (repo_root or REPO_ROOT) / "ai-docs" + if not docs.is_dir(): + return [] + names: list[str] = [] + for path in sorted(docs.iterdir()): + if not path.is_dir() or path.name.startswith("."): + continue + quality = path / "quality" + if quality.is_dir() and any(quality.glob("*.yaml")): + names.append(path.name) + return names + + +def quality_packs_for_tests( + project: str | None = None, + *, + repo_root: Path | None = None, + environ: dict[str, str] | None = None, +) -> list[ProjectPaths]: + """ + Quality packs to exercise in harness unit tests. + + Resolution order: + 1. Explicit ``project`` argument + 2. ``REQUIREMENTS_PROJECT`` env + 3. Every discovered ``ai-docs/*/quality`` pack + """ + env = environ if environ is not None else os.environ + chosen = (project or env.get("REQUIREMENTS_PROJECT") or "").strip() + if chosen: + paths = resolve_project(chosen, repo_root=repo_root) + if not paths.questions_dir.is_dir(): + raise FileNotFoundError( + f"No quality directory for project {chosen!r}: {paths.questions_dir}" + ) + if not any(paths.questions_dir.glob("*.yaml")): + raise FileNotFoundError( + f"No quality/*.yaml for project {chosen!r}: {paths.questions_dir}" + ) + return [paths] + + names = discover_quality_projects(repo_root=repo_root) + if not names: + raise FileNotFoundError( + "No ai-docs//quality/*.yaml packs found; " + "add questions or set REQUIREMENTS_PROJECT" + ) + return [resolve_project(name, repo_root=repo_root) for name in names] + + +def load_vocabulary(path: Path | None) -> str: + if path is None or not path.is_file(): + return "" + return path.read_text(encoding="utf-8").strip() + + +def add_project_args(parser: argparse.ArgumentParser) -> None: + parser.add_argument( + "--project", + help="Project folder under ai-docs/ (sets --root/--questions/--vocabulary)", + ) + parser.add_argument("--root", type=Path, help="Tree of requirements.yaml catalogs") + parser.add_argument( + "--questions", + type=Path, + help="Directory of quality question *.yaml files", + ) + parser.add_argument( + "--vocabulary", + type=Path, + help="Optional vocabulary markdown prepended to each Laya state", + ) + + +def paths_from_args(args: argparse.Namespace) -> ProjectPaths: + if getattr(args, "project", None): + paths = resolve_project(args.project) + root = Path(args.root) if getattr(args, "root", None) else paths.requirements_root + questions = ( + Path(args.questions) if getattr(args, "questions", None) else paths.questions_dir + ) + vocabulary = ( + Path(args.vocabulary) if getattr(args, "vocabulary", None) else paths.vocabulary_path + ) + return ProjectPaths( + name=paths.name, + requirements_root=root, + questions_dir=questions, + vocabulary_path=vocabulary, + ) + + root = getattr(args, "root", None) + questions = getattr(args, "questions", None) + if not root or not questions: + raise SystemExit("Pass --project NAME, or both --root and --questions") + + root = Path(root) + questions = Path(questions) + vocabulary = Path(args.vocabulary) if getattr(args, "vocabulary", None) else ( + questions / "vocabulary.md" + ) + return ProjectPaths( + name=None, + requirements_root=root, + questions_dir=questions, + vocabulary_path=vocabulary, + ) diff --git a/.agents/skills/manage-requirements/quality/requirements-schema.txt b/.agents/skills/manage-requirements/quality/requirements-schema.txt new file mode 100644 index 0000000000..5b9e0426eb --- /dev/null +++ b/.agents/skills/manage-requirements/quality/requirements-schema.txt @@ -0,0 +1,2 @@ +# Pinned deps for the schema/heuristic CI job (wheels only via --only-binary). +PyYAML==6.0.3 diff --git a/.agents/skills/manage-requirements/quality/requirements.txt b/.agents/skills/manage-requirements/quality/requirements.txt new file mode 100644 index 0000000000..4cc69d6646 --- /dev/null +++ b/.agents/skills/manage-requirements/quality/requirements.txt @@ -0,0 +1,5 @@ +# Optional local/CI extras for the Laya quality job. +# Schema/heuristic gates use requirements-schema.txt (pinned PyYAML). +PyYAML==6.0.3 +laya>=0.3.21,<0.4 +laya-evals>=0.1.0 diff --git a/.agents/skills/manage-requirements/quality/run_laya_eval.sh b/.agents/skills/manage-requirements/quality/run_laya_eval.sh new file mode 100755 index 0000000000..2dd5c6a39c --- /dev/null +++ b/.agents/skills/manage-requirements/quality/run_laya_eval.sh @@ -0,0 +1,33 @@ +#!/usr/bin/env bash +# Run requirement quality evals for a project (heuristic gate always; Laya when requested). +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +cd "$SCRIPT_DIR" + +PYTHON="${PYTHON:-python3}" +PROJECT="${REQUIREMENTS_PROJECT:-college-v2}" +SOURCE="${LAYA_SOURCE:-heuristic}" +REPORT_DIR="${REPORT_DIR:-$SCRIPT_DIR/report}" +mkdir -p "$REPORT_DIR" + +PROJECT_ARGS=(--project "$PROJECT") + +"$PYTHON" load_questions.py "${PROJECT_ARGS[@]}" +"$PYTHON" build_gold.py "${PROJECT_ARGS[@]}" +"$PYTHON" -m unittest test_quality_harness.py + +"$PYTHON" judge_catalog.py "${PROJECT_ARGS[@]}" --source heuristic --report "$REPORT_DIR/catalog_snapshot.json" + +if [[ "$SOURCE" != "laya" ]]; then + echo "Skipping Laya catalog eval (LAYA_SOURCE=$SOURCE)." + exit 0 +fi + +if ! "$PYTHON" -c "import laya" >/dev/null 2>&1; then + echo "Laya is not installed. pip install -r requirements.txt" >&2 + exit 1 +fi + +"$PYTHON" judge_catalog.py "${PROJECT_ARGS[@]}" --source laya --report "$REPORT_DIR/catalog_snapshot_laya.json" +"$PYTHON" judge_extra.py "${PROJECT_ARGS[@]}" --report "$REPORT_DIR/extra-answers.json" diff --git a/.agents/skills/manage-requirements/quality/test_quality_harness.py b/.agents/skills/manage-requirements/quality/test_quality_harness.py new file mode 100644 index 0000000000..7c2ab3b3a2 --- /dev/null +++ b/.agents/skills/manage-requirements/quality/test_quality_harness.py @@ -0,0 +1,453 @@ +from __future__ import annotations + +import json +import shutil +import sys +import tempfile +import unittest +from pathlib import Path + +import yaml + +DIR = Path(__file__).resolve().parent +sys.path.insert(0, str(DIR)) + +from extract_requirement_states import ( + iter_requirement_rows, + requirement_has_stub_ac, + requirement_line_numbers, +) +from judge_catalog import ( + format_failure_detail, + format_quality_report, + heuristic_answers, + report_quality_failures, + snapshot_from_rows, +) +from judge_extra import judge_extra_answers +from load_questions import ( + defect_criteria_from_questions, + is_global_qc, + load_question_documents, + noul_question_ids, + question_applies, + targeted_laya_by_requirement, + validate_questions, +) +from project import ProjectPaths, quality_packs_for_tests + + +def write_yaml(path: Path, data: dict) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(yaml.safe_dump(data, sort_keys=False), encoding="utf-8") + + +def pack_questions(pack: ProjectPaths) -> list[dict]: + return load_question_documents(pack.questions_dir) + + +def pack_noul_ids(pack: ProjectPaths) -> tuple[str, ...]: + return noul_question_ids(pack_questions(pack)) + + +def install_global_questions( + questions_dir: Path, + pack: ProjectPaths, + extra: dict[str, dict] | None = None, +) -> None: + """Copy applies.all question YAML from the project quality pack into the fixture.""" + questions_dir.mkdir(parents=True, exist_ok=True) + copied = 0 + for question in pack_questions(pack): + if not is_global_qc(question): + continue + src = Path(question["path"]) + shutil.copy2(src, questions_dir / src.name) + copied += 1 + if copied == 0: + raise RuntimeError( + f"No global QC questions (applies.all) in {pack.questions_dir}" + ) + for name, payload in (extra or {}).items(): + write_yaml(questions_dir / f"{name}.yaml", payload) + + +def sample_catalog(*, stub: bool = False) -> dict: + then = "X" if stub else "The matcher writes matchMode Auto or Manual" + given = ( + "The feature is available in an active sample case" + if stub + else "A course with a resolved institution is match-eligible" + ) + when = "The behavior is exercised" if stub else "Matching runs" + return { + "specId": "sample-feature", + "kind": "component", + "title": "Sample feature", + "requirements": [ + { + "id": "FR-001", + "requirementType": "Functional", + "title": "X", + "statement": "Matching records a concrete matchMode.", + "priority": "High", + "status": "Draft", + "acceptanceCriteria": [ + {"given": given, "when": when, "then": then}, + ], + }, + { + "id": "FR-002", + "requirementType": "Functional", + "title": "Observable outcome", + "statement": "Save persists the chosen articulation type.", + "priority": "High", + "status": "Draft", + "acceptanceCriteria": [ + { + "given": "A course is open in evaluation", + "when": "The reviewer saves Direct transferable equivalency", + "then": "articulation.type is Direct and acronym is T-EQ", + } + ], + }, + ], + } + + +def build_fixture( + tmp: str | Path, + pack: ProjectPaths, + *, + stub: bool = False, + extra_questions: dict[str, dict] | None = None, +) -> tuple[Path, Path, list[dict]]: + root = Path(tmp) + req_root = root / "requirements" + questions_dir = root / "quality" + write_yaml( + req_root / "components" / "sample-feature" / "requirements.yaml", + sample_catalog(stub=stub), + ) + install_global_questions(questions_dir, pack, extra_questions) + rows = iter_requirement_rows(req_root, repo_root=root) + return req_root, questions_dir, rows + + +class ProjectPackTestCase(unittest.TestCase): + """Harness tests that need a project's quality/*.yaml as the question source.""" + + def quality_packs(self) -> list[ProjectPaths]: + return quality_packs_for_tests() + + +class ExtractTests(ProjectPackTestCase): + def test_iter_rows_from_catalog(self): + for pack in self.quality_packs(): + with self.subTest(project=pack.name): + with tempfile.TemporaryDirectory() as tmp: + _, _, rows = build_fixture(tmp, pack) + self.assertEqual(len(rows), 2) + self.assertEqual( + {row["id"] for row in rows}, + {"sample-feature#FR-001", "sample-feature#FR-002"}, + ) + self.assertTrue(all(row["sourceLine"] for row in rows)) + + def test_stub_ac_detection(self): + for pack in self.quality_packs(): + with self.subTest(project=pack.name): + with tempfile.TemporaryDirectory() as good_tmp, tempfile.TemporaryDirectory() as bad_tmp: + _, _, good_rows = build_fixture(good_tmp, pack, stub=False) + _, _, bad_rows = build_fixture(bad_tmp, pack, stub=True) + by_good = {row["id"]: row for row in good_rows} + by_bad = {row["id"]: row for row in bad_rows} + self.assertFalse(by_good["sample-feature#FR-001"]["stub_ac"]) + self.assertTrue(by_bad["sample-feature#FR-001"]["stub_ac"]) + self.assertTrue( + requirement_has_stub_ac( + { + "title": "X", + "acceptanceCriteria": [ + { + "given": "The feature is available in an active sample case", + "when": "The behavior is exercised", + "then": "X", + } + ], + } + ) + ) + + +class QualityGateTests(ProjectPackTestCase): + def test_heuristic_marks_stub_ac(self): + for pack in self.quality_packs(): + with self.subTest(project=pack.name): + rows = [ + {"id": "good#FR-001", "stub_ac": False}, + {"id": "bad#FR-001", "stub_ac": True}, + ] + answers = {row["id"]: heuristic_answers(row) for row in rows} + snap = snapshot_from_rows( + rows, answers, "heuristic", pack_noul_ids(pack) + ) + self.assertEqual(snap["failedIds"], ["bad#FR-001"]) + self.assertEqual(snap["lowConfidenceCount"], 0) + + def test_report_includes_rich_failure_location(self): + current = { + "requirementCount": 2, + "failedIds": ["sample-feature#FR-001", "other-feature#FR-001"], + "failures": [ + { + "id": "sample-feature#FR-001", + "requirementId": "FR-001", + "title": "Sample rows", + "sourcePath": "requirements/components/sample-feature/requirements.yaml", + "sourceLine": 12, + "reasons": ["testable", "verifiable"], + "primary_defect": "stub_ac", + }, + { + "id": "other-feature#FR-001", + "requirementId": "FR-001", + "title": "Other entry", + "sourcePath": "requirements/screens/other-feature/requirements.yaml", + "sourceLine": 10, + "reasons": ["testable", "verifiable"], + "primary_defect": "stub_ac", + }, + ], + "lowConfidenceCount": 0, + } + report = "\n".join(format_quality_report(current, color=False)) + self.assertIn("Requirements analyzed: 2", report) + self.assertIn("Passed: 0", report) + self.assertIn("Failed: 2", report) + self.assertIn( + "✖ requirements/components/sample-feature/requirements.yaml#12 FR-001: Sample rows [FAILED]", + report, + ) + self.assertIn("Failed checks: [testable, verifiable]", report) + self.assertIn("Reason: stub acceptance criteria", report) + + def test_clean_catalog_has_no_report(self): + current = { + "requirementCount": 1, + "failedIds": [], + "failures": [], + "lowConfidenceCount": 0, + } + self.assertEqual(report_quality_failures(current), []) + + def test_format_failure_detail_includes_quality_ids(self): + lines = format_failure_detail( + { + "id": "sample-feature#FR-002", + "requirementId": "FR-002", + "title": "Observable outcome", + "sourcePath": "requirements/components/sample-feature/requirements.yaml", + "sourceLine": 28, + "reasons": ["verifiable", "testable"], + "primary_defect": "stub_ac", + }, + color=False, + ) + self.assertEqual( + lines, + [ + "✖ requirements/components/sample-feature/requirements.yaml#28 FR-002: Observable outcome [FAILED]", + "Failed checks: [verifiable, testable]", + "Reason: stub acceptance criteria", + ], + ) + + def test_source_line_matches_yaml_id_entry(self): + text = ( + "requirements:\n" + " - id: FR-001\n" + " title: First\n" + " - id: FR-002\n" + " title: Second\n" + ) + lines = requirement_line_numbers(text) + self.assertEqual(lines["FR-001"], 2) + self.assertEqual(lines["FR-002"], 4) + + def test_fixture_stub_failures_appear_in_report(self): + for pack in self.quality_packs(): + with self.subTest(project=pack.name): + with tempfile.TemporaryDirectory() as tmp: + _, questions_dir, rows = build_fixture(tmp, pack, stub=True) + questions = load_question_documents(questions_dir) + answers = {row["id"]: heuristic_answers(row) for row in rows} + current = snapshot_from_rows( + rows, answers, "heuristic", noul_question_ids(questions) + ) + report = report_quality_failures( + current, defect_info=defect_criteria_from_questions(questions) + ) + self.assertTrue(report) + self.assertTrue( + any("stub acceptance criteria" in line for line in report) + ) + self.assertIn("sample-feature#FR-001", current["failedIds"]) + self.assertNotIn("sample-feature#FR-002", current["failedIds"]) + + +class QuestionYamlTests(ProjectPackTestCase): + def test_quality_packs_have_global_qc(self): + packs = self.quality_packs() + self.assertTrue(packs) + for pack in packs: + with self.subTest(project=pack.name): + questions = pack_questions(pack) + globals_ = [q for q in questions if is_global_qc(q)] + self.assertTrue(pack.questions_dir.is_dir()) + self.assertGreaterEqual(len(globals_), 1) + self.assertTrue(pack_noul_ids(pack)) + + def test_questions_validate_against_fixture_catalog(self): + for pack in self.quality_packs(): + with self.subTest(project=pack.name): + with tempfile.TemporaryDirectory() as tmp: + _, questions_dir, rows = build_fixture( + tmp, + pack, + extra_questions={ + "uses_match_mode": { + "id": "uses_match_mode", + "type": "check", + "applies": {"ids": ["sample-feature#FR-001"]}, + "checks": [{"type": "contains", "text": "matchMode"}], + }, + "save_writes_type": { + "id": "save_writes_type", + "type": "noul", + "applies": {"ids": ["sample-feature#FR-002"]}, + "instructions": "Does save write articulation.type?", + "expected": True, + }, + }, + ) + self.assertEqual(validate_questions(rows, questions_dir), []) + questions = load_question_documents(questions_dir) + extra = targeted_laya_by_requirement(rows, questions) + self.assertEqual(set(extra), {"sample-feature#FR-002"}) + self.assertIn("save_writes_type", extra["sample-feature#FR-002"]) + + def test_global_applies_to_every_requirement(self): + row = { + "id": "x#FR-001", + "specId": "x", + "kind": "script", + "requirementType": "NonFunctional", + "reqTags": [], + } + self.assertTrue(question_applies({"applies": {"all": True}}, row)) + self.assertFalse(question_applies({"applies": {"ids": ["other#FR-001"]}}, row)) + self.assertTrue(question_applies({"applies": {"kinds": ["script"]}}, row)) + self.assertFalse(question_applies({"applies": {"kinds": ["screen"]}}, row)) + + def test_unknown_applies_id_fails(self): + for pack in self.quality_packs(): + with self.subTest(project=pack.name): + with tempfile.TemporaryDirectory() as tmp: + _, questions_dir, rows = build_fixture(tmp, pack) + write_yaml( + questions_dir / "scoped.yaml", + { + "id": "scoped", + "type": "noul", + "applies": {"ids": ["sample-feature#FR-999"]}, + "instructions": "x", + "expected": True, + }, + ) + errors = validate_questions(rows, questions_dir) + self.assertTrue(any("FR-999" in err for err in errors)) + + def test_check_contains_missing_text_fails(self): + for pack in self.quality_packs(): + with self.subTest(project=pack.name): + with tempfile.TemporaryDirectory() as tmp: + _, questions_dir, rows = build_fixture(tmp, pack) + write_yaml( + questions_dir / "bad_check.yaml", + { + "id": "bad_check", + "type": "check", + "applies": {"ids": ["sample-feature#FR-001"]}, + "checks": [{"type": "contains", "text": "ace_id"}], + }, + ) + errors = validate_questions(rows, questions_dir) + self.assertTrue(any("expected to contain" in err for err in errors)) + + def test_extra_answer_mismatch(self): + errors = judge_extra_answers( + {"sample-feature#FR-002": {"save_writes_type": {"noul": 0.1}}}, + {"sample-feature#FR-002": {"save_writes_type": True}}, + ) + self.assertEqual(len(errors), 1) + + def test_extra_cannot_reuse_global_ids(self): + for pack in self.quality_packs(): + with self.subTest(project=pack.name): + reserved = pack_noul_ids(pack)[0] + errors = judge_extra_answers( + {"x#FR-001": {reserved: {"noul": 0.9}}}, + {"x#FR-001": {reserved: True}}, + reserved_ids={reserved}, + ) + self.assertTrue(any("collides" in err for err in errors)) + + +class GoldBuildTests(ProjectPackTestCase): + def test_build_gold_writes_extra_jsonl(self): + import build_gold + + for pack in self.quality_packs(): + with self.subTest(project=pack.name): + with tempfile.TemporaryDirectory() as tmp: + req_root, questions_dir, _ = build_fixture( + tmp, + pack, + extra_questions={ + "save_writes_type": { + "id": "save_writes_type", + "type": "noul", + "applies": {"ids": ["sample-feature#FR-002"]}, + "instructions": "Does save write articulation.type?", + "expected": True, + }, + }, + ) + extra = Path(tmp) / "extra.jsonl" + self.assertEqual( + build_gold.main( + [ + "--root", + str(req_root), + "--questions", + str(questions_dir), + "--extra-out", + str(extra), + ] + ), + 0, + ) + extra_lines = [ + json.loads(line) + for line in extra.read_text(encoding="utf-8").splitlines() + if line + ] + self.assertEqual(len(extra_lines), 1) + self.assertIn("save_writes_type", extra_lines[0]["questions"]) + for global_id in pack_noul_ids(pack): + self.assertNotIn(global_id, extra_lines[0]["questions"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/.agents/skills/manage-requirements/schemas/requirement.schema.json b/.agents/skills/manage-requirements/schemas/requirement.schema.json new file mode 100644 index 0000000000..164d2e2245 --- /dev/null +++ b/.agents/skills/manage-requirements/schemas/requirement.schema.json @@ -0,0 +1,196 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "requirement.schema.json", + "title": "Requirement", + "type": "object", + "required": [ + "id", + "requirementType", + "title", + "statement", + "priority", + "status" + ], + "properties": { + "id": { + "type": "string", + "pattern": "^(FR|NFR)-[0-9]{3,}$" + }, + "requirementType": { + "type": "string", + "enum": ["Functional", "NonFunctional"] + }, + "title": { + "type": "string", + "minLength": 3 + }, + "statement": { + "type": "string", + "minLength": 10 + }, + "description": { + "type": "string" + }, + "priority": { + "type": "string", + "enum": ["Critical", "High", "Medium", "Low"] + }, + "status": { + "type": "string", + "enum": [ + "Draft", + "Proposed", + "Approved", + "Implemented", + "Verified", + "Deprecated" + ] + }, + "source": { + "type": "string" + }, + "rationale": { + "type": "string" + }, + "owner": { + "type": "string" + }, + "tags": { + "type": "array", + "items": { + "type": "string" + } + }, + "category": { + "type": "string" + }, + "acceptanceCriteria": { + "type": "array", + "items": { + "$ref": "#/$defs/acceptanceCriterion" + } + }, + "metrics": { + "type": "array", + "items": { + "$ref": "#/$defs/metric" + } + }, + "verificationMethod": { + "type": "string", + "enum": ["Test", "Inspection", "Analysis", "Demonstration", "Audit"] + }, + "dependencies": { + "type": "array", + "items": { + "type": "string" + } + }, + "constraints": { + "type": "array", + "items": { + "type": "string" + } + }, + "assumptions": { + "type": "array", + "items": { + "type": "string" + } + }, + "traceability": { + "$ref": "#/$defs/traceability" + } + }, + "$defs": { + "acceptanceCriterion": { + "type": "object", + "required": ["given", "when", "then"], + "properties": { + "given": { + "type": "string" + }, + "when": { + "type": "string" + }, + "then": { + "type": "string" + } + } + }, + "metric": { + "type": "object", + "required": ["name", "operator", "value"], + "properties": { + "name": { + "type": "string" + }, + "operator": { + "type": "string", + "enum": ["<", "<=", "=", ">=", ">"] + }, + "value": { + "type": ["number", "string"] + }, + "unit": { + "type": "string" + } + } + }, + "traceability": { + "type": "object", + "properties": { + "businessObjectives": { + "type": "array", + "items": { + "type": "string" + } + }, + "epics": { + "type": "array", + "items": { + "type": "string" + } + }, + "features": { + "type": "array", + "items": { + "type": "string" + } + }, + "testCases": { + "type": "array", + "items": { + "type": "string" + } + } + } + } + }, + "allOf": [ + { + "if": { + "properties": { + "requirementType": { + "const": "Functional" + } + } + }, + "then": { + "required": ["acceptanceCriteria"] + } + }, + { + "if": { + "properties": { + "requirementType": { + "const": "NonFunctional" + } + } + }, + "then": { + "required": ["category", "metrics", "verificationMethod"] + } + } + ] +} diff --git a/.agents/skills/manage-requirements/schemas/requirements-catalog.schema.json b/.agents/skills/manage-requirements/schemas/requirements-catalog.schema.json new file mode 100644 index 0000000000..73214d09ad --- /dev/null +++ b/.agents/skills/manage-requirements/schemas/requirements-catalog.schema.json @@ -0,0 +1,47 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "requirements-catalog.schema.json", + "title": "RequirementsCatalog", + "description": "Feature-level catalog of requirements for a reusable component, screen, or script. Cross-project; not tied to a single domain.", + "type": "object", + "required": ["specId", "kind", "title", "requirements"], + "additionalProperties": false, + "properties": { + "specId": { + "type": "string", + "minLength": 2, + "description": "Stable feature id, usually the folder basename (e.g. articulation-section)." + }, + "kind": { + "type": "string", + "enum": ["component", "screen", "script"] + }, + "title": { + "type": "string", + "minLength": 3 + }, + "description": { + "type": "string" + }, + "config": { + "type": "object", + "description": "Declarative knobs the feature exposes so requirements stay reusable (props, ports, section ids).", + "additionalProperties": true + }, + "dependsOn": { + "type": "array", + "items": { + "type": "string", + "minLength": 1 + }, + "description": "Other catalog specId values this feature composes (e.g. screens depending on components)." + }, + "requirements": { + "type": "array", + "minItems": 1, + "items": { + "$ref": "requirement.schema.json" + } + } + } +} diff --git a/.agents/skills/manage-requirements/scripts/__tests__/validate-requirements.test.js b/.agents/skills/manage-requirements/scripts/__tests__/validate-requirements.test.js new file mode 100644 index 0000000000..948ad890dc --- /dev/null +++ b/.agents/skills/manage-requirements/scripts/__tests__/validate-requirements.test.js @@ -0,0 +1,209 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { test, beforeEach, afterEach } = require('node:test'); + +const { + collectAcceptanceQuality, + collectYamlFiles, + isStubCriterion, + main, + validateFiles, + validateMarkdownPair, +} = require('../validate-requirements'); + +const VALID_YAML = `specId: example-feature +kind: component +title: Example feature +description: Short summary of what this catalog covers. +config: + props: + - readonly +dependsOn: [] +requirements: + - id: FR-001 + requirementType: Functional + title: Example behavior + statement: The component must expose the configured behavior without hard-coding a specific screen. + priority: High + status: Draft + tags: [example] + acceptanceCriteria: + - given: The component is configured with readonly true + when: The user opens the feature + then: Editing controls are disabled +`; + +function writeCatalog(dir, { specId = 'example-feature', yaml = VALID_YAML, markdown = true } = {}) { + const featureDir = path.join(dir, specId); + fs.mkdirSync(featureDir, { recursive: true }); + fs.writeFileSync(path.join(featureDir, 'requirements.yaml'), yaml, 'utf8'); + if (markdown) { + fs.writeFileSync(path.join(featureDir, `${specId}.md`), `# ${specId}\n\nPurpose.\n`, 'utf8'); + } + return path.join(featureDir, 'requirements.yaml'); +} + +let tmpDir; + +beforeEach(() => { + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'req-validate-')); +}); + +afterEach(() => { + fs.rmSync(tmpDir, { recursive: true, force: true }); +}); + +test('collectYamlFiles finds nested requirements.yaml', () => { + writeCatalog(tmpDir); + const files = collectYamlFiles(tmpDir); + assert.equal(files.length, 1); + assert.match(files[0], /example-feature\/requirements\.yaml$/); +}); + +test('valid catalog with companion markdown passes', () => { + const yamlPath = writeCatalog(tmpDir); + const [result] = validateFiles([yamlPath]); + assert.equal(result.ok, true); + assert.deepEqual(result.errors, []); + assert.deepEqual(result.warnings, []); +}); + +test('YAML parse error fails the catalog', () => { + const yamlPath = writeCatalog(tmpDir, { + yaml: 'specId: [this is: broken', + }); + const [result] = validateFiles([yamlPath]); + assert.equal(result.ok, false); + assert.match(result.errors[0], /YAML parse error/); +}); + +test('duplicate requirement ids fail', () => { + const yaml = VALID_YAML.replace( + 'then: Editing controls are disabled\n', + `then: Editing controls are disabled + - id: FR-001 + requirementType: Functional + title: Duplicate behavior + statement: Another statement that is long enough for the schema. + priority: High + status: Draft + acceptanceCriteria: + - given: The component is configured with readonly false + when: The user opens the feature + then: Editing controls remain enabled +` + ); + const yamlPath = writeCatalog(tmpDir, { yaml }); + const [result] = validateFiles([yamlPath]); + assert.equal(result.ok, false); + assert.ok(result.errors.some((err) => /duplicate id "FR-001"/.test(err))); +}); + +test('functional requirement without acceptanceCriteria fails schema', () => { + const yaml = `specId: example-feature +kind: component +title: Example feature +requirements: + - id: FR-001 + requirementType: Functional + title: Example behavior + statement: The component must expose the configured behavior without hard-coding a specific screen. + priority: High + status: Draft +`; + const yamlPath = writeCatalog(tmpDir, { yaml }); + const [result] = validateFiles([yamlPath]); + assert.equal(result.ok, false); + assert.ok(result.errors.some((err) => /required/.test(err))); +}); + +test('missing companion markdown fails', () => { + const yamlPath = writeCatalog(tmpDir, { markdown: false }); + const [result] = validateFiles([yamlPath]); + assert.equal(result.ok, false); + assert.ok(result.errors.some((err) => /missing companion markdown/.test(err))); + assert.ok(validateMarkdownPair(yamlPath, { specId: 'example-feature' }).length > 0); +}); + +test('README.md satisfies the markdown pair', () => { + const yamlPath = writeCatalog(tmpDir, { markdown: false }); + fs.writeFileSync(path.join(path.dirname(yamlPath), 'README.md'), '# Example\n', 'utf8'); + const [result] = validateFiles([yamlPath]); + assert.equal(result.ok, true); +}); + +test('short given/when/then warn instead of failing', () => { + const yaml = VALID_YAML.replace( + 'given: The component is configured with readonly true', + 'given: short' + ); + const yamlPath = writeCatalog(tmpDir, { yaml }); + const [result] = validateFiles([yamlPath]); + assert.equal(result.ok, true); + assert.ok(result.warnings.some((warn) => /given shorter than 8/.test(warn))); +}); + +test('empty given/when/then fail', () => { + const yaml = VALID_YAML.replace( + 'given: The component is configured with readonly true', + 'given: " "' + ); + const yamlPath = writeCatalog(tmpDir, { yaml }); + const [result] = validateFiles([yamlPath]); + assert.equal(result.ok, false); + assert.ok(result.errors.some((err) => /given must not be empty/.test(err))); +}); + +test('placeholder given/when is a stub AC warning, not a hard fail', () => { + const yaml = VALID_YAML.replace( + ` - given: The component is configured with readonly true + when: The user opens the feature + then: Editing controls are disabled +`, + ` - given: The feature is available in an active CollegeV2 case + when: The behavior is exercised + then: Editing controls are disabled +` + ); + const yamlPath = writeCatalog(tmpDir, { yaml }); + const [result] = validateFiles([yamlPath]); + assert.equal(result.ok, true); + assert.ok(result.warnings.some((warn) => /stub acceptance criterion/.test(warn))); +}); + +test('then that repeats the title is a stub AC', () => { + assert.equal( + isStubCriterion( + { title: 'Hide student search in Web Entry' }, + { given: 'A screen is open today', when: 'The reviewer continues', then: 'Hide student search in Web Entry' } + ), + true + ); + const quality = collectAcceptanceQuality({ + requirements: [ + { + id: 'FR-001', + title: 'Hide student search in Web Entry', + acceptanceCriteria: [ + { + given: 'A screen is open today', + when: 'The reviewer continues', + then: 'Hide student search in Web Entry', + }, + ], + }, + ], + }); + assert.equal(quality.errors.length, 0); + assert.equal(quality.warnings.length, 1); +}); + +test('CLI main returns 0 for a valid tree and 1 when markdown is missing', () => { + writeCatalog(tmpDir); + assert.equal(main([tmpDir]), 0); + const brokenDir = path.join(tmpDir, 'broken'); + writeCatalog(brokenDir, { specId: 'missing-md', markdown: false }); + assert.equal(main([brokenDir]), 1); +}); diff --git a/.agents/skills/manage-requirements/scripts/check-requirements.js b/.agents/skills/manage-requirements/scripts/check-requirements.js new file mode 100644 index 0000000000..3f18b65bf6 --- /dev/null +++ b/.agents/skills/manage-requirements/scripts/check-requirements.js @@ -0,0 +1,154 @@ +#!/usr/bin/env node +/** + * Run schema validation + heuristic quality judging for requirement catalogs. + * + * Usage: + * node check-requirements.js + * node check-requirements.js college-v2 + * node check-requirements.js --project military + * + * With no project arg, checks every ai-docs//requirements tree. + * Project may also come from REQUIREMENTS_PROJECT when no CLI project is given. + */ + +const { spawnSync } = require('child_process'); +const fs = require('fs'); +const path = require('path'); + +const SKILL_ROOT = path.resolve(__dirname, '..'); +const REPO_ROOT = path.resolve(SKILL_ROOT, '../../..'); +const AI_DOCS = path.join(REPO_ROOT, 'ai-docs'); +const VALIDATE_JS = path.join(__dirname, 'validate-requirements.js'); +const JUDGE_PY = path.join(SKILL_ROOT, 'quality', 'judge_catalog.py'); + +const colors = { + reset: '\x1b[0m', + red: '\x1b[31m', + green: '\x1b[32m', + yellow: '\x1b[33m', + cyan: '\x1b[36m', +}; + +function log(message, color = 'reset') { + console.log(`${colors[color]}${message}${colors.reset}`); +} + +function parseArgs(argv) { + let project = null; + const rest = []; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === '--project' || arg === '-p') { + project = argv[i + 1] || null; + i += 1; + continue; + } + if (arg.startsWith('--project=')) { + project = arg.slice('--project='.length) || null; + continue; + } + if (arg.startsWith('-')) { + rest.push(arg); + continue; + } + if (project === null) { + project = arg; + continue; + } + rest.push(arg); + } + if (!project && process.env.REQUIREMENTS_PROJECT) { + project = process.env.REQUIREMENTS_PROJECT; + } + return { project, rest }; +} + +function listRequirementProjects() { + if (!fs.existsSync(AI_DOCS)) { + return []; + } + return fs + .readdirSync(AI_DOCS, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .filter((name) => fs.existsSync(path.join(AI_DOCS, name, 'requirements'))) + .sort(); +} + +function hasQualityFixtures(project) { + const qualityDir = path.join(AI_DOCS, project, 'quality'); + if (!fs.existsSync(qualityDir)) { + return false; + } + return fs.readdirSync(qualityDir).some((name) => name.endsWith('.yaml')); +} + +function run(command, args, options = {}) { + const result = spawnSync(command, args, { + cwd: options.cwd || REPO_ROOT, + env: { ...process.env, FORCE_COLOR: process.env.FORCE_COLOR || '1' }, + stdio: 'inherit', + }); + if (result.error) { + log(result.error.message, 'red'); + return 1; + } + return typeof result.status === 'number' ? result.status : 1; +} + +function main(argv = process.argv.slice(2)) { + const { project } = parseArgs(argv); + const projects = project ? [project] : listRequirementProjects(); + + if (projects.length === 0) { + log('No ai-docs/*/requirements trees found.', 'red'); + return 1; + } + + if (project) { + const reqRoot = path.join(AI_DOCS, project, 'requirements'); + if (!fs.existsSync(reqRoot)) { + log(`Requirements tree missing: ${path.relative(REPO_ROOT, reqRoot)}`, 'red'); + return 1; + } + } + + const schemaTargets = projects.map((name) => path.join(AI_DOCS, name, 'requirements')); + log(`Schema: validating ${projects.join(', ')}...`, 'cyan'); + const schemaStatus = run(process.execPath, [VALIDATE_JS, ...schemaTargets]); + if (schemaStatus !== 0) { + return schemaStatus; + } + + let qualityFailed = 0; + for (const name of projects) { + if (!hasQualityFixtures(name)) { + log(`Quality: skip ${name} (no ai-docs/${name}/quality/*.yaml)`, 'yellow'); + continue; + } + log(`Quality: judging ${name} (heuristic)...`, 'cyan'); + const status = run('python3', [JUDGE_PY, '--project', name, '--source', 'heuristic']); + if (status !== 0) { + qualityFailed += 1; + } + } + + if (qualityFailed > 0) { + log(`${qualityFailed} project quality gate(s) failed.`, 'red'); + return 1; + } + + log('Schema and quality checks passed.', 'green'); + return 0; +} + +module.exports = { + hasQualityFixtures, + listRequirementProjects, + main, + parseArgs, +}; + +if (require.main === module) { + process.exit(main()); +} diff --git a/.agents/skills/manage-requirements/scripts/validate-requirements.js b/.agents/skills/manage-requirements/scripts/validate-requirements.js new file mode 100644 index 0000000000..692dcb927b --- /dev/null +++ b/.agents/skills/manage-requirements/scripts/validate-requirements.js @@ -0,0 +1,390 @@ +#!/usr/bin/env node +/** + * Validate requirements.yaml catalogs against the manage-requirements schemas. + * + * Usage: + * node .agents/skills/manage-requirements/scripts/validate-requirements.js [path...] + * + * Paths may be a requirements.yaml file, a feature directory, or a tree root. + * Default: every ai-docs//requirements tree that exists. + */ + +const fs = require('fs'); +const path = require('path'); +const yaml = require('js-yaml'); +const Ajv = require('ajv/dist/2020'); +const addFormats = require('ajv-formats'); + +const SKILL_ROOT = path.resolve(__dirname, '..'); +const SCHEMA_DIR = path.join(SKILL_ROOT, 'schemas'); +const REPO_ROOT = path.resolve(SKILL_ROOT, '../../..'); +const AI_DOCS = path.join(REPO_ROOT, 'ai-docs'); +const AC_FIELD_MIN_LENGTH = 8; + +function defaultTargets() { + if (!fs.existsSync(AI_DOCS)) { + return []; + } + return fs + .readdirSync(AI_DOCS, { withFileTypes: true }) + .filter((entry) => entry.isDirectory()) + .map((entry) => path.join(AI_DOCS, entry.name, 'requirements')) + .filter((dir) => fs.existsSync(dir)) + .sort(); +} + +const DEFAULT_TARGET = path.join(REPO_ROOT, 'ai-docs/college-v2/requirements'); +const PLACEHOLDER_GIVEN = /the feature is available/i; +const PLACEHOLDER_WHEN = /the behavior is exercised/i; + +const colors = { + reset: '\x1b[0m', + red: '\x1b[31m', + green: '\x1b[32m', + yellow: '\x1b[33m', + cyan: '\x1b[36m', + bright: '\x1b[1m', +}; + +function log(message, color = 'reset') { + console.log(`${colors[color]}${message}${colors.reset}`); +} + +function loadJson(filePath) { + return JSON.parse(fs.readFileSync(filePath, 'utf8')); +} + +function createAjv() { + const ajv = new Ajv({ + allErrors: true, + strict: false, + validateSchema: true, + }); + addFormats(ajv); + + const requirementSchema = loadJson(path.join(SCHEMA_DIR, 'requirement.schema.json')); + const catalogSchema = loadJson(path.join(SCHEMA_DIR, 'requirements-catalog.schema.json')); + + ajv.addSchema(requirementSchema); + ajv.addSchema(catalogSchema); + + return { + ajv, + validateCatalog: ajv.getSchema('requirements-catalog.schema.json'), + }; +} + +function collectYamlFiles(targetPath) { + const abs = path.resolve(targetPath); + if (!fs.existsSync(abs)) { + throw new Error(`Path not found: ${abs}`); + } + + const stat = fs.statSync(abs); + if (stat.isFile()) { + if (!abs.endsWith('.yaml') && !abs.endsWith('.yml')) { + throw new Error(`Not a YAML file: ${abs}`); + } + return [abs]; + } + + if (stat.isDirectory()) { + const direct = path.join(abs, 'requirements.yaml'); + if (fs.existsSync(direct)) { + return [direct]; + } + + const found = []; + const walk = (dir) => { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) { + walk(full); + } else if (entry.name === 'requirements.yaml' || entry.name === 'requirements.yml') { + found.push(full); + } + } + }; + walk(abs); + return found.sort(); + } + + throw new Error(`Unsupported path: ${abs}`); +} + +function formatAjvErrors(errors) { + if (!errors || errors.length === 0) { + return ['Unknown validation error']; + } + return errors.map((err) => { + const instance = err.instancePath || '/'; + return `${instance} ${err.message}${err.params ? ` ${JSON.stringify(err.params)}` : ''}`; + }); +} + +function normalizeComparable(value) { + return String(value || '') + .toLowerCase() + .replace(/\s+/g, ' ') + .trim(); +} + +function companionMarkdownPath(filePath, specId) { + const dir = path.dirname(filePath); + const candidates = []; + if (typeof specId === 'string' && specId.length > 0) { + candidates.push(path.join(dir, `${specId}.md`)); + } + candidates.push(path.join(dir, 'README.md')); + return candidates.find((candidate) => fs.existsSync(candidate)) || null; +} + +function validateMarkdownPair(filePath, data) { + const specId = data && typeof data.specId === 'string' ? data.specId : null; + if (companionMarkdownPath(filePath, specId)) { + return []; + } + const expected = specId ? `${specId}.md or README.md` : '.md or README.md'; + return [`missing companion markdown (${expected}) in ${path.dirname(filePath)}`]; +} + +function isStubCriterion(req, criterion) { + const given = String(criterion.given || ''); + const when = String(criterion.when || ''); + const then = normalizeComparable(criterion.then); + const title = normalizeComparable(req.title); + const placeholderPair = PLACEHOLDER_GIVEN.test(given) && PLACEHOLDER_WHEN.test(when); + const thenRepeatsTitle = then.length > 0 && then === title; + return placeholderPair || thenRepeatsTitle; +} + +/** @deprecated Use isStubCriterion */ +function isTautologicalCriterion(req, criterion) { + return isStubCriterion(req, criterion); +} + +function collectAcceptanceQuality(data) { + const errors = []; + const warnings = []; + if (!data || !Array.isArray(data.requirements)) { + return { errors, warnings }; + } + + data.requirements.forEach((req, reqIndex) => { + if (!req || !Array.isArray(req.acceptanceCriteria)) { + return; + } + req.acceptanceCriteria.forEach((criterion, acIndex) => { + if (!criterion || typeof criterion !== 'object') { + return; + } + ['given', 'when', 'then'].forEach((field) => { + const value = typeof criterion[field] === 'string' ? criterion[field].trim() : ''; + const instance = `/requirements/${reqIndex}/acceptanceCriteria/${acIndex}/${field}`; + if (value.length === 0) { + errors.push(`${instance} must not be empty`); + } else if (value.length < AC_FIELD_MIN_LENGTH) { + warnings.push( + `${instance} shorter than ${AC_FIELD_MIN_LENGTH} characters` + ); + } + }); + if (isStubCriterion(req, criterion)) { + const id = typeof req.id === 'string' ? req.id : `#${reqIndex}`; + warnings.push( + `/requirements/${reqIndex} ${id} stub acceptance criterion (placeholder given/when or then repeats title)` + ); + } + }); + }); + + return { errors, warnings }; +} + +function validateCatalogDocument(filePath, data, validateCatalog) { + const errors = []; + + if (!validateCatalog(data)) { + for (const msg of formatAjvErrors(validateCatalog.errors)) { + errors.push(msg); + } + } + + if (data && Array.isArray(data.requirements)) { + const seen = new Set(); + data.requirements.forEach((req, index) => { + if (!req || typeof req.id !== 'string') { + return; + } + if (seen.has(req.id)) { + errors.push(`/requirements/${index}/id duplicate id "${req.id}" within catalog`); + } + seen.add(req.id); + }); + } + + return errors; +} + +function indexSpecIds(yamlFiles) { + const bySpecId = new Map(); + for (const file of yamlFiles) { + try { + const data = yaml.load(fs.readFileSync(file, 'utf8')); + if (data && typeof data.specId === 'string') { + bySpecId.set(data.specId, file); + } + } catch { + // parse errors reported during validation + } + } + return bySpecId; +} + +function validateDependsOn(data, filePath, specIndex) { + const errors = []; + if (!data || !Array.isArray(data.dependsOn)) { + return errors; + } + for (const dep of data.dependsOn) { + if (!specIndex.has(dep)) { + errors.push( + `dependsOn "${dep}" not found among catalogs in this validation run (referenced from ${path.relative(REPO_ROOT, filePath)})` + ); + } + } + return errors; +} + +function validateFiles(files, options = {}) { + const { validateCatalog } = options.validateCatalog + ? { validateCatalog: options.validateCatalog } + : createAjv(); + if (!validateCatalog) { + throw new Error('Failed to compile requirements-catalog.schema.json'); + } + + const uniqueFiles = [...new Set(files)]; + const specIndex = indexSpecIds(uniqueFiles); + const results = []; + + for (const file of uniqueFiles) { + let data; + try { + data = yaml.load(fs.readFileSync(file, 'utf8')); + } catch (err) { + results.push({ + file, + ok: false, + errors: [`YAML parse error: ${err.message}`], + warnings: [], + data: null, + }); + continue; + } + + const quality = collectAcceptanceQuality(data); + const errors = [ + ...validateCatalogDocument(file, data, validateCatalog), + ...validateMarkdownPair(file, data), + ...validateDependsOn(data, file, specIndex), + ...quality.errors, + ]; + + results.push({ + file, + ok: errors.length === 0, + errors, + warnings: quality.warnings, + data, + }); + } + + return results; +} + +function main(argv = process.argv.slice(2)) { + const targets = argv.length > 0 ? argv : defaultTargets(); + + if (targets.length === 0) { + log('No ai-docs/*/requirements trees found.', 'red'); + log('Pass an explicit path to a requirements.yaml, feature dir, or tree.', 'yellow'); + return 1; + } + + let files = []; + try { + for (const target of targets) { + files = files.concat(collectYamlFiles(target)); + } + } catch (err) { + log(err.message, 'red'); + return 1; + } + + files = [...new Set(files)]; + + if (files.length === 0) { + log('No requirements.yaml files found.', 'yellow'); + return 1; + } + + log(`Validating ${files.length} catalog(s)...`, 'cyan'); + const results = validateFiles(files); + let failed = 0; + let warningCount = 0; + + for (const result of results) { + const rel = path.relative(REPO_ROOT, result.file) || result.file; + if (!result.ok) { + failed += 1; + log(`FAIL ${rel}`, 'red'); + for (const err of result.errors) { + log(` ${err}`, 'red'); + } + } else { + const count = result.data && Array.isArray(result.data.requirements) + ? result.data.requirements.length + : 0; + const specId = result.data && result.data.specId ? result.data.specId : 'unknown'; + log(`OK ${rel} (${specId}, ${count} requirements)`, 'green'); + } + for (const warning of result.warnings) { + warningCount += 1; + log(` WARN ${warning}`, 'yellow'); + } + } + + console.log(''); + if (failed > 0) { + log(`${failed} of ${results.length} catalog(s) failed.`, 'red'); + return 1; + } + + log(`All ${results.length} catalog(s) passed.`, 'green'); + if (warningCount > 0) { + log(`${warningCount} acceptance-criterion warning(s).`, 'yellow'); + } + return 0; +} + +module.exports = { + AC_FIELD_MIN_LENGTH, + DEFAULT_TARGET, + REPO_ROOT, + collectAcceptanceQuality, + collectYamlFiles, + companionMarkdownPath, + createAjv, + isStubCriterion, + isTautologicalCriterion, + main, + validateCatalogDocument, + validateDependsOn, + validateFiles, + validateMarkdownPair, +}; + +if (require.main === module) { + process.exit(main()); +} diff --git a/.agents/skills/manage-requirements/templates/feature.md.example b/.agents/skills/manage-requirements/templates/feature.md.example new file mode 100644 index 0000000000..2d9d02915e --- /dev/null +++ b/.agents/skills/manage-requirements/templates/feature.md.example @@ -0,0 +1,22 @@ +# Example feature + +Narrative for humans and agents. Do not duplicate every FR statement here. + +## Purpose + +What this feature does and who uses it. + +## Kind and reuse + +- `kind`: component | screen | script +- Configurable via `config` in `requirements.yaml` +- Screens compose components through `dependsOn` + +## Related assets + +- Vue / BPMN / script paths as applicable +- Legacy design or edge-case docs during migration + +## Configuration + +Describe how consumers configure this feature (props, ports, section order). diff --git a/.agents/skills/manage-requirements/templates/requirements.yaml.example b/.agents/skills/manage-requirements/templates/requirements.yaml.example new file mode 100644 index 0000000000..1f6cd435f0 --- /dev/null +++ b/.agents/skills/manage-requirements/templates/requirements.yaml.example @@ -0,0 +1,23 @@ +specId: example-feature +kind: component +title: Example feature +description: Short summary of what this catalog covers. +config: + props: + - readonly + - allowedActions +dependsOn: [] +requirements: + - id: FR-001 + requirementType: Functional + title: Example behavior + statement: The component must expose the configured behavior without hard-coding a specific screen. + priority: High + status: Draft + tags: [example, reusable] + acceptanceCriteria: + - given: The component is configured with readonly true + when: The user opens the feature + then: Editing controls are disabled + traceability: + testCases: [] diff --git a/.env.example b/.env.example index c451173583..db64cc3770 100644 --- a/.env.example +++ b/.env.example @@ -35,6 +35,8 @@ REDIS_PREFIX= HORIZON_PREFIX=horizon: PM4_HORIZON_SUPERVISOR_BPMN_MAX_JOBS=10 PM4_HORIZON_SUPERVISOR_1_MAX_JOBS=100 +# Local-directory plugin installs (artisan plugin:install); API always requires https:// URLs +PLUGIN_INSTALL_ALLOW_LOCAL_PATH=false DOCKER_SHARED_MEMORY=256m # Comma-separated load balancer / proxy IPs only (do not use * in production) PROXIES= diff --git a/.gitignore b/.gitignore index 1d764fc458..c2a2469215 100644 --- a/.gitignore +++ b/.gitignore @@ -58,3 +58,4 @@ storage/transitions **/caddy frankenphp frankenphp-worker.php +Caddyfile.edge diff --git a/ProcessMaker/Assets/DataSourcesInProcess.php b/ProcessMaker/Assets/DataSourcesInProcess.php index 0a44452214..2a45c90be3 100644 --- a/ProcessMaker/Assets/DataSourcesInProcess.php +++ b/ProcessMaker/Assets/DataSourcesInProcess.php @@ -25,7 +25,7 @@ public function referencesToExport(Process $process, array $dataSources = []) // Data Sources used in BPMN Service Tasks $xpath = new DOMXPath($process->getDefinitions()); $xpath->registerNamespace('pm', WorkflowServiceProvider::PROCESS_MAKER_NS); - + // Find all nodes with pm:config $nodes = $xpath->query("//*[@pm:config!='']"); foreach ($nodes as $node) { diff --git a/ProcessMaker/Assets/DataSourcesInScreen.php b/ProcessMaker/Assets/DataSourcesInScreen.php index 4a7494d74f..c10e9b8c9e 100644 --- a/ProcessMaker/Assets/DataSourcesInScreen.php +++ b/ProcessMaker/Assets/DataSourcesInScreen.php @@ -2,9 +2,9 @@ namespace ProcessMaker\Assets; +use Illuminate\Support\Arr; use ProcessMaker\Managers\ExportManager; use ProcessMaker\Models\Screen; -use Illuminate\Support\Arr; class DataSourcesInScreen { diff --git a/ProcessMaker/Console/Commands/ChangeKeyEncryptedData.php b/ProcessMaker/Console/Commands/ChangeKeyEncryptedData.php index feab536017..4804129199 100644 --- a/ProcessMaker/Console/Commands/ChangeKeyEncryptedData.php +++ b/ProcessMaker/Console/Commands/ChangeKeyEncryptedData.php @@ -4,8 +4,8 @@ use Exception; use Illuminate\Console\Command; -use ProcessMaker\Facades\EncryptedData; use Illuminate\Support\Facades\Log; +use ProcessMaker\Facades\EncryptedData; class ChangeKeyEncryptedData extends Command { diff --git a/ProcessMaker/Console/Commands/CreateSamlCertificate.php b/ProcessMaker/Console/Commands/CreateSamlCertificate.php index edfc5c34e9..99b0bf5433 100644 --- a/ProcessMaker/Console/Commands/CreateSamlCertificate.php +++ b/ProcessMaker/Console/Commands/CreateSamlCertificate.php @@ -16,7 +16,7 @@ class CreateSamlCertificate extends CreateCertificate {--keyname=key.pem : Full name of the certificate key file} {--certname=cert.pem : Full name to the certificate file} {--subject= : Set subject of request or cert ' - . '(e.g. /C=US/ST=New York/L=New York City/O=Example Inc/CN=example.com)}'; + . '(e.g. /C=US/ST=New York/L=New York City/O=Example Inc/CN=example.com)}'; /** * The console command description. diff --git a/ProcessMaker/Console/Commands/PluginInstallCommand.php b/ProcessMaker/Console/Commands/PluginInstallCommand.php new file mode 100644 index 0000000000..29eb3f58dc --- /dev/null +++ b/ProcessMaker/Console/Commands/PluginInstallCommand.php @@ -0,0 +1,81 @@ +argument('repo'); + $branch = $this->option('branch'); + $tag = $this->option('tag'); + + // Set up event listener to output log messages + $listener = function (PluginLog $event) { + $message = $event->message; + if ($event->pluginName) { + $message = "[{$event->pluginName}] {$message}"; + } + + switch ($event->status) { + case 'done': + $this->info($message); + break; + case 'error': + $this->error($message); + break; + case 'running': + default: + $this->line($message); + break; + } + + // Stop listening if we get a 'done' or 'error' status + if (in_array($event->status, ['done', 'error'])) { + Event::forget(PluginLog::class); + } + }; + + Event::listen(PluginLog::class, $listener); + + try { + $manager = new PluginManager(); + $manager->install($repo, $branch, $tag); + + return Command::SUCCESS; + } catch (RuntimeException $e) { + $this->error('Installation failed: ' . $e->getMessage()); + event(new PluginLog('Installation failed: ' . $e->getMessage(), 'error')); + + return Command::FAILURE; + } finally { + // Clean up listener + Event::forget(PluginLog::class); + } + } +} diff --git a/ProcessMaker/Console/Commands/PluginListCommand.php b/ProcessMaker/Console/Commands/PluginListCommand.php new file mode 100644 index 0000000000..5e7d43bde5 --- /dev/null +++ b/ProcessMaker/Console/Commands/PluginListCommand.php @@ -0,0 +1,55 @@ +list(); + + if (empty($plugins)) { + $this->info('No plugins installed.'); + + return Command::SUCCESS; + } + + $headers = ['Name', 'Description', 'Branch/Tag']; + $rows = []; + + foreach ($plugins as $plugin) { + $rows[] = [ + $plugin['name'], + $plugin['description'], + $plugin['branch'] ?? 'N/A', + ]; + } + + $this->table($headers, $rows); + + return Command::SUCCESS; + } +} diff --git a/ProcessMaker/Console/Commands/PluginPublishTenantAssets.php b/ProcessMaker/Console/Commands/PluginPublishTenantAssets.php new file mode 100644 index 0000000000..73f0152640 --- /dev/null +++ b/ProcessMaker/Console/Commands/PluginPublishTenantAssets.php @@ -0,0 +1,84 @@ +resolveTenantContext(); + if ($tenantId === null) { + return self::FAILURE; + } + + $folder = $this->argument('pluginFolder'); + + if ($folder) { + return $this->publishSinglePlugin($publisher, (string) $folder, $tenantId); + } + + return $this->publishAllPlugins($publisher, $tenantId); + } + + private function resolveTenantContext(): ?int + { + if (!config('app.multitenancy')) { + $this->error('Multitenancy is disabled. This command only applies when MULTITENANCY=true.'); + + return null; + } + + $tenantId = PluginVendorAssets::currentTenantId(); + if ($tenantId === null) { + $this->error('No current tenant. Run with TENANT= or through tenants:artisan.'); + + return null; + } + + return $tenantId; + } + + private function publishSinglePlugin( + TenantPluginAssetPublisher $publisher, + string $folder, + int $tenantId, + ): int { + $pluginPath = storage_path('plugins/' . $folder); + if (!is_dir($pluginPath)) { + $this->error("Plugin folder not found: {$pluginPath}"); + + return self::FAILURE; + } + + $published = $publisher->publishPlugin($pluginPath, $tenantId); + $this->info($published + ? "Published {$folder} for tenant {$tenantId}." + : "Skipped {$folder}: no public directory."); + + return self::SUCCESS; + } + + private function publishAllPlugins(TenantPluginAssetPublisher $publisher, int $tenantId): int + { + foreach ($publisher->publishAllInstalledPlugins($tenantId) as $name => $published) { + $this->line(($published ? 'Published ' : 'Skipped ') . $name); + } + + return self::SUCCESS; + } +} diff --git a/ProcessMaker/Console/Commands/PluginReloadListenCommand.php b/ProcessMaker/Console/Commands/PluginReloadListenCommand.php new file mode 100644 index 0000000000..78eab41ff0 --- /dev/null +++ b/ProcessMaker/Console/Commands/PluginReloadListenCommand.php @@ -0,0 +1,122 @@ +shouldListen($cycle)) { + $cycle++; + + try { + $this->catchUp($reload); + $this->disableReadTimeout(); + $this->info('Listening for plugin runtime reloads on [' . $reload->channel() . '].'); + $this->subscribe($reload); + $this->warn('Plugin reload subscription ended. Reconnecting.'); + } catch (Throwable $exception) { + $this->warn( + 'Plugin reload listener lost Redis: ' . $exception->getMessage() . ' Reconnecting.' + ); + } + + if (!$this->shouldListen($cycle)) { + break; + } + + $this->releaseRedis(); + $this->pauseBeforeReconnect(); + } + + return self::SUCCESS; + } + + private function shouldListen(int $cycle): bool + { + $maxCycles = (int) config('plugin_manager.reload_listen_max_cycles', 0); + + return $maxCycles === 0 || $cycle < $maxCycles; + } + + /** + * PhpRedis treats a read timeout of 0 as PHP's default_socket_timeout. + * A subscribe with no messages then dies with "read error on connection". + */ + private function disableReadTimeout(): void + { + ini_set('default_socket_timeout', '-1'); + + $client = Redis::connection()->client(); + if (is_object($client) && method_exists($client, 'setOption')) { + $client->setOption(\Redis::OPT_READ_TIMEOUT, -1); + } + } + + private function catchUp(PluginRuntimeReload $reload): void + { + $remoteVersion = $reload->remoteVersion(); + if ($remoteVersion > $reload->appliedVersion()) { + $this->applyReload($reload, $remoteVersion); + } + } + + private function subscribe(PluginRuntimeReload $reload): void + { + Redis::subscribe([$reload->channel()], function (string $message) use ($reload): void { + $version = $reload->versionFromMessage($message); + if ($version <= $reload->appliedVersion()) { + return; + } + + $this->applyReload($reload, $version, $reload->tenantIdFromMessage($message)); + }); + } + + private function releaseRedis(): void + { + try { + Redis::purge('default'); + } catch (Throwable) { + // The broken connection is discarded on the next attempt. + } + } + + private function pauseBeforeReconnect(): void + { + $seconds = max(0, (int) config('plugin_manager.reload_reconnect_delay', 1)); + if ($seconds > 0) { + sleep($seconds); + } + } + + private function applyReload(PluginRuntimeReload $reload, int $version, ?string $tenantId = null): bool + { + if ($version > 0 && !$reload->rememberApplied($version)) { + $this->error('Could not record the applied plugin reload version.'); + + return false; + } + + if (!$reload->scheduleSupervisorRestart($tenantId)) { + $this->error('Could not schedule the local supervisor restart.'); + + return false; + } + + $this->info('Scheduled supervisorctl restart on this pod.'); + + return true; + } +} diff --git a/ProcessMaker/Console/Commands/PluginUninstallCommand.php b/ProcessMaker/Console/Commands/PluginUninstallCommand.php new file mode 100644 index 0000000000..4b3038a7f6 --- /dev/null +++ b/ProcessMaker/Console/Commands/PluginUninstallCommand.php @@ -0,0 +1,79 @@ +argument('name'); + + // Set up event listener to output log messages + $listener = function (PluginLog $event) { + $message = $event->message; + if ($event->pluginName) { + $message = "[{$event->pluginName}] {$message}"; + } + + switch ($event->status) { + case 'done': + $this->info($message); + break; + case 'error': + $this->error($message); + break; + case 'running': + default: + $this->line($message); + break; + } + + // Stop listening if we get a 'done' or 'error' status + if (in_array($event->status, ['done', 'error'])) { + Event::forget(PluginLog::class); + } + }; + + Event::listen(PluginLog::class, $listener); + + try { + $manager = new PluginManager(); + $manager->uninstall($name); + + return Command::SUCCESS; + } catch (RuntimeException $e) { + $this->error('Uninstallation failed: ' . $e->getMessage()); + event(new PluginLog('Uninstallation failed: ' . $e->getMessage(), 'error', $name)); + + return Command::FAILURE; + } finally { + // Clean up listener + Event::forget(PluginLog::class); + } + } +} diff --git a/ProcessMaker/Console/Commands/TenantsOctaneSync.php b/ProcessMaker/Console/Commands/TenantsOctaneSync.php new file mode 100644 index 0000000000..6258b28ec6 --- /dev/null +++ b/ProcessMaker/Console/Commands/TenantsOctaneSync.php @@ -0,0 +1,168 @@ +option('dry-run'); + + $this->warnIfDryRun($dryRun); + + $result = $this->runSync($sync, $dryRun); + if ($result === null) { + return self::FAILURE; + } + + $this->displaySyncOverview($result); + $this->displayTenantPlans($result); + $this->displayFileChanges($result, $dryRun); + + return $this->finishWithSupervisor($sync, $dryRun); + } + + private function warnIfDryRun(bool $dryRun): void + { + if ($dryRun) { + $this->warn('Dry run: no files will be written or removed.'); + } + } + + /** + * @return array|null + */ + private function runSync(OctaneTenantRuntimeSync $sync, bool $dryRun): ?array + { + try { + return $sync->sync($dryRun); + } catch (Throwable $exception) { + $this->error($exception->getMessage()); + + return null; + } + } + + /** + * @param array $result + */ + private function displaySyncOverview(array $result): void + { + $this->info('Mode: ' . $result['mode']); + $this->line('Supervisor dir: ' . config('octane_tenants.supervisor_dir')); + $this->line('Edge Caddyfile: ' . config('octane_tenants.edge_caddyfile')); + } + + /** + * @param array $result + */ + private function displayTenantPlans(array $result): void + { + if ($result['tenants'] !== []) { + $this->table( + ['Tenant ID', 'Domain', 'Octane port', 'Admin port'], + collect($result['tenants'])->map(fn (array $plan) => [ + $plan['id'], + $plan['domain'], + $plan['port'], + $plan['admin_port'], + ])->all() + ); + + return; + } + + if ($result['mode'] === 'multitenant') { + $this->warn('No tenants found in the landlord database.'); + } + } + + /** + * @param array $result + */ + private function displayFileChanges(array $result, bool $dryRun): void + { + $this->displayPathList($result['written'], $dryRun, '+', 'Would write', 'Wrote'); + $this->displayPathList($result['removed'], $dryRun, '-', 'Would remove', 'Removed'); + } + + /** + * @param list $paths + */ + private function displayPathList( + array $paths, + bool $dryRun, + string $marker, + string $dryRunLabel, + string $appliedLabel, + ): void { + if ($paths === []) { + return; + } + + $this->info(($dryRun ? $dryRunLabel : $appliedLabel) . ':'); + foreach ($paths as $path) { + $this->line(' ' . $marker . ' ' . $path); + } + } + + private function finishWithSupervisor(OctaneTenantRuntimeSync $sync, bool $dryRun): int + { + if (! $this->option('apply')) { + $this->comment('Files synced. Run with --apply to execute supervisorctl reread/update.'); + + return self::SUCCESS; + } + + if ($dryRun) { + $this->warn('Skipping --apply during dry run.'); + + return self::SUCCESS; + } + + return $this->applySupervisor($sync); + } + + private function applySupervisor(OctaneTenantRuntimeSync $sync): int + { + try { + $output = $sync->applySupervisor(); + } catch (Throwable $exception) { + $this->error($exception->getMessage()); + + return self::FAILURE; + } + + if ($output !== '') { + $this->line($output); + } + $this->info('supervisorctl reread/update completed.'); + + return self::SUCCESS; + } +} \ No newline at end of file diff --git a/ProcessMaker/Console/Commands/TransitionExecutors.php b/ProcessMaker/Console/Commands/TransitionExecutors.php index c235d528aa..dd8eb386a4 100644 --- a/ProcessMaker/Console/Commands/TransitionExecutors.php +++ b/ProcessMaker/Console/Commands/TransitionExecutors.php @@ -53,7 +53,7 @@ public function handle(): int // Get the optional timeout $timeout = $this->option('timeout') ?? 300; - if ((int)$timeout <= 60) { + if ((int) $timeout <= 60) { $this->error('Timeout must be a greater or equal to 60'); return 1; @@ -88,14 +88,14 @@ public function handle(): int $response = $this->scriptMicroserviceService->updateCustomExecutor($executors[$index]); Log::debug('Response', ['response' => $response]); - $status = strtolower((string)($response['status'] ?? '')); + $status = strtolower((string) ($response['status'] ?? '')); // Send subscription message (Pusher protocol example) $client->send(json_encode([ 'event' => 'pusher:subscribe', 'data' => [ - 'channel' => "build-image-" . $executors[$index]->uuid - ] + 'channel' => 'build-image-' . $executors[$index]->uuid, + ], ])); $running = true; @@ -123,7 +123,6 @@ public function handle(): int if (!$error) { $this->info("Executor {$executors[$index]->uuid} transitioned successfully." . PHP_EOL); } - } catch (RequestException $e) { $this->error("Request failed for executor {$executors[$index]->uuid}"); $this->line(PHP_EOL); @@ -136,47 +135,45 @@ public function handle(): int $client->close(); $index++; - } while ($index < $total); } - return 0; } private function getExecutors($uuid): Collection { $query = ScriptExecutor::query() - ->where("is_system", 0) + ->where('is_system', 0) ->where(function ($query) { $query - ->whereNotIn("title", [ - "PHP Executor", - "Node Executor", - "Python Executor", - "C# Executor", - "Java Executor" + ->whereNotIn('title', [ + 'PHP Executor', + 'Node Executor', + 'Python Executor', + 'C# Executor', + 'Java Executor', ]) - ->orWhereNotIn("description", [ - "Default PHP Executor", - "Default Javascript/Node Executor", - "Default Python Executor", - "Default C# Executor", - "Default Java Executor" + ->orWhereNotIn('description', [ + 'Default PHP Executor', + 'Default Javascript/Node Executor', + 'Default Python Executor', + 'Default C# Executor', + 'Default Java Executor', ]); }) - ->whereNotIn("language", ["php-nayra", "lua", "javascript-ssr", "sql"]) - ->whereNotNull("config") + ->whereNotIn('language', ['php-nayra', 'lua', 'javascript-ssr', 'sql']) + ->whereNotNull('config') ->where(function ($query) { $query - ->where("type", ScriptExecutorType::Custom) - ->orWhereNull("type"); + ->where('type', ScriptExecutorType::Custom) + ->orWhereNull('type'); }); if (is_array($uuid) && !empty($uuid)) { - $query->whereIn("uuid", $uuid); - } else if (is_string($uuid)) { - $query->where("uuid", $uuid); + $query->whereIn('uuid', $uuid); + } elseif (is_string($uuid)) { + $query->where('uuid', $uuid); } return $query->get(); diff --git a/ProcessMaker/Console/Commands/UpdateSettingsGroupId.php b/ProcessMaker/Console/Commands/UpdateSettingsGroupId.php index 02804f9ccb..fa213146c7 100644 --- a/ProcessMaker/Console/Commands/UpdateSettingsGroupId.php +++ b/ProcessMaker/Console/Commands/UpdateSettingsGroupId.php @@ -32,6 +32,7 @@ public function handle() { // Update the setting.group_id with the corresponding category created in settings_menus Setting::updateAllSettingsGroupId(); - return $this->info("Settings group_id updated successfully"); + + return $this->info('Settings group_id updated successfully'); } } diff --git a/ProcessMaker/Contracts/ConditionalRedirectServiceInterface.php b/ProcessMaker/Contracts/ConditionalRedirectServiceInterface.php index e46e390096..fdece68e6e 100644 --- a/ProcessMaker/Contracts/ConditionalRedirectServiceInterface.php +++ b/ProcessMaker/Contracts/ConditionalRedirectServiceInterface.php @@ -6,7 +6,6 @@ /** * @see \ProcessMaker\Services\ConditionalRedirectService - * @package ProcessMaker\Contracts */ interface ConditionalRedirectServiceInterface { diff --git a/ProcessMaker/Contracts/ScriptModuleInterface.php b/ProcessMaker/Contracts/ScriptModuleInterface.php new file mode 100644 index 0000000000..c0e72fadd2 --- /dev/null +++ b/ProcessMaker/Contracts/ScriptModuleInterface.php @@ -0,0 +1,35 @@ +all(). + */ +interface ScriptModuleInterface +{ + /** + * Unique key used as the script variable name (e.g. "collections"). + */ + public static function key(): string; + + /** + * Human-readable label for docs / UI catalog. + */ + public static function label(): string; + + /** + * Method catalog for discovery (key => meta). + * + * @return array> + */ + public static function catalog(): array; + + /** + * Prepare the module for a single script execution. + */ + public function boot(ScriptExecutionContext $context): void; +} diff --git a/ProcessMaker/Contracts/ServiceTaskImplementationInterface.php b/ProcessMaker/Contracts/ServiceTaskImplementationInterface.php index a1800f7995..96eb345e01 100644 --- a/ProcessMaker/Contracts/ServiceTaskImplementationInterface.php +++ b/ProcessMaker/Contracts/ServiceTaskImplementationInterface.php @@ -14,7 +14,10 @@ interface ServiceTaskImplementationInterface * @param array $config * @param string $tokenId * - * @return string $tokenId + * @return mixed + * + * Implementations may accept an optional 4th argument `$timeout` (seconds). + * WorkflowManager passes it when available (see CoreServiceTask). */ public function run(array $data, array $config, $tokenId = ''); } diff --git a/ProcessMaker/Contracts/WorkflowManagerInterface.php b/ProcessMaker/Contracts/WorkflowManagerInterface.php index 1776f30245..9b1be65189 100644 --- a/ProcessMaker/Contracts/WorkflowManagerInterface.php +++ b/ProcessMaker/Contracts/WorkflowManagerInterface.php @@ -181,10 +181,11 @@ public function existsServiceImplementation($implementation); * @param array $data * @param array $config * @param string $tokenId + * @param int|float $timeout * * @return mixed */ - public function runServiceImplementation($implementation, array $data, array $config, $tokenId = ''); + public function runServiceImplementation($implementation, array $data, array $config, $tokenId = '', $timeout = 0); /** * Get the service task class implementation diff --git a/ProcessMaker/Events/ActivityAssigned.php b/ProcessMaker/Events/ActivityAssigned.php index e1d77abddf..169f07d1bc 100644 --- a/ProcessMaker/Events/ActivityAssigned.php +++ b/ProcessMaker/Events/ActivityAssigned.php @@ -71,7 +71,7 @@ public function getProcessRequest() /** * Return the process request token. * - * @return \ProcessMaker\Models\ProcessRequestToken + * @return ProcessRequestToken */ public function getProcessRequestToken() { diff --git a/ProcessMaker/Events/ActivityCompleted.php b/ProcessMaker/Events/ActivityCompleted.php index 83e99c8b36..7e69679741 100644 --- a/ProcessMaker/Events/ActivityCompleted.php +++ b/ProcessMaker/Events/ActivityCompleted.php @@ -51,7 +51,7 @@ public function broadcastOn() /** * Return the process request. * - * @return \ProcessMaker\Models\ProcessRequestToken + * @return ProcessRequestToken */ public function getProcessRequestToken() { diff --git a/ProcessMaker/Events/CustomizeUiUpdated.php b/ProcessMaker/Events/CustomizeUiUpdated.php index 17137eade7..86db58a684 100644 --- a/ProcessMaker/Events/CustomizeUiUpdated.php +++ b/ProcessMaker/Events/CustomizeUiUpdated.php @@ -31,7 +31,7 @@ class CustomizeUiUpdated implements SecurityLogEventInterface private function defaultVariables(): string { $defaults = config('app.default_colors'); - + $objects = []; foreach ($defaults as $name => $value) { $objects[] = [ @@ -40,10 +40,10 @@ private function defaultVariables(): string 'title' => ucfirst($name), ]; } - + return json_encode($objects); } - + /** * Create a new event instance. * diff --git a/ProcessMaker/Events/PluginLog.php b/ProcessMaker/Events/PluginLog.php new file mode 100644 index 0000000000..6855c8f0b9 --- /dev/null +++ b/ProcessMaker/Events/PluginLog.php @@ -0,0 +1,65 @@ +message = $message; + $this->status = $status; + $this->pluginName = $pluginName; + $this->userId = $userId; + } + + public function broadcastAs() + { + return 'PluginLog'; + } + + public function broadcastOn() + { + return new PrivateChannel('ProcessMaker.Models.User.' . $this->userId); + } +} diff --git a/ProcessMaker/Events/ProcessCompleted.php b/ProcessMaker/Events/ProcessCompleted.php index 566fd59730..af37cbd0cb 100644 --- a/ProcessMaker/Events/ProcessCompleted.php +++ b/ProcessMaker/Events/ProcessCompleted.php @@ -57,7 +57,7 @@ public function broadcastOn() /** * Return the process request. * - * @return \ProcessMaker\Models\ProcessRequest + * @return ProcessRequest */ public function getProcessRequest() { diff --git a/ProcessMaker/Events/RedirectToEvent.php b/ProcessMaker/Events/RedirectToEvent.php index df05b8b010..4b2e1b6639 100644 --- a/ProcessMaker/Events/RedirectToEvent.php +++ b/ProcessMaker/Events/RedirectToEvent.php @@ -45,16 +45,17 @@ public function broadcastOn(): array { $channels = [ // Current request - new PrivateChannel('ProcessMaker.Models.ProcessRequest.' . $this->processRequest->getKey()) + new PrivateChannel('ProcessMaker.Models.ProcessRequest.' . $this->processRequest->getKey()), ]; // include child requests if any - foreach($this->processRequest->childRequests()->pluck('id') as $childRequestId) { + foreach ($this->processRequest->childRequests()->pluck('id') as $childRequestId) { $channels[] = new PrivateChannel('ProcessMaker.Models.ProcessRequest.' . $childRequestId); } // include parent request if any if ($this->processRequest->parent_request_id) { $channels[] = new PrivateChannel('ProcessMaker.Models.ProcessRequest.' . $this->processRequest->parent_request_id); } + return $channels; } } diff --git a/ProcessMaker/Events/SessionStarted.php b/ProcessMaker/Events/SessionStarted.php index c55631656c..9ee5aa96ac 100644 --- a/ProcessMaker/Events/SessionStarted.php +++ b/ProcessMaker/Events/SessionStarted.php @@ -32,7 +32,7 @@ public function __construct(User $user) /** * Get the channels the event should broadcast on. * - * @return \Illuminate\Broadcasting\Channel|array + * @return Channel|array */ public function broadcastOn() { diff --git a/ProcessMaker/Exception/MissingBpmnReferenceException.php b/ProcessMaker/Exception/MissingBpmnReferenceException.php new file mode 100644 index 0000000000..5aec7b716e --- /dev/null +++ b/ProcessMaker/Exception/MissingBpmnReferenceException.php @@ -0,0 +1,11 @@ +canAnyFirst('view-users|view-groups|view-auth_clients|manage-public-files|view-settings')) { - case 'view-users': - return redirect()->route('users.index'); - case 'view-groups': - return redirect()->route('groups.index'); - case 'view-auth_clients': - return redirect()->route('auth-clients.index'); - case 'manage-public-files': - return redirect()->route('file-manager.index'); - case 'view-settings': - return redirect()->route('settings.index'); - default: - throw new AuthorizationException(); + $permission = \Auth::user()->canAnyFirst( + 'view-users|view-groups|view-auth_clients|manage-public-files|view-settings|view-plugins', + ); + + $routesByPermission = [ + 'view-users' => 'users.index', + 'view-groups' => 'groups.index', + 'view-auth_clients' => 'auth-clients.index', + 'manage-public-files' => 'file-manager.index', + 'view-settings' => 'settings.index', + 'view-plugins' => 'plugins.index', + ]; + + $route = $routesByPermission[$permission] ?? null; + + if ($route === null) { + throw new AuthorizationException(); } + + return redirect()->route($route); } } diff --git a/ProcessMaker/Http/Controllers/Api/Concerns/AppliesDeployVersionName.php b/ProcessMaker/Http/Controllers/Api/Concerns/AppliesDeployVersionName.php new file mode 100644 index 0000000000..e202a6c3b6 --- /dev/null +++ b/ProcessMaker/Http/Controllers/Api/Concerns/AppliesDeployVersionName.php @@ -0,0 +1,63 @@ + $rules + * @return array + */ + protected function deployRulesForUpdate(array $rules, bool $isUpdate): array + { + return $this->deployVersionName()->mergeRules($rules, $isUpdate); + } + + protected function ensureDeployVersionHistoryAvailable(bool $isUpdate): ?JsonResponse + { + if ($isUpdate && !$this->deployVersionName()->canRecordHistory()) { + return response()->json([ + 'success' => false, + 'message' => 'Version history (package-versions) is required to publish asset updates.', + ], 422); + } + + return null; + } + + protected function latestPublishedVersionId(Model $asset): int + { + return $this->deployVersionName()->latestPublishedVersionId($asset); + } + + protected function applyDeployVersionName( + Model $asset, + Request $request, + bool $isUpdate, + int $publishedVersionIdBefore, + ): void { + $versionName = $request->input('version_name'); + $description = $request->input('version_description'); + + $this->deployVersionName()->applyAfterSave( + $asset, + is_string($versionName) ? $versionName : null, + (int) $request->user()->id, + $isUpdate, + $publishedVersionIdBefore, + is_string($description) ? $description : null, + ); + } +} diff --git a/ProcessMaker/Http/Controllers/Api/DeployProcess.php b/ProcessMaker/Http/Controllers/Api/DeployProcess.php new file mode 100644 index 0000000000..b9abdb2695 --- /dev/null +++ b/ProcessMaker/Http/Controllers/Api/DeployProcess.php @@ -0,0 +1,267 @@ +input('name'); + $isUpdate = Process::where('name', $name)->exists(); + // Alternative B writes drafts or B versions, not asset version history. + $needsVersionName = $isUpdate && !$this->targetsAlternativeB($request); + + if ($unavailable = $this->ensureDeployVersionHistoryAvailable($needsVersionName)) { + return $unavailable; + } + + $validator = Validator::make( + $request->all(), + $this->deployRulesForUpdate([ + 'bpmn' => 'required|string', + 'name' => 'required|string|max:255', + 'description' => 'nullable|string|max:65535', + 'process_category_name' => 'nullable|string|max:255', + 'alternative' => 'nullable|in:A,B', + 'publish' => 'nullable|boolean', + ], $needsVersionName), + ); + + if ($validator->fails()) { + return response()->json([ + 'success' => false, + 'errors' => $validator->errors(), + ], 422); + } + + return $this->saveDeployedProcess($request); + } + + private function saveDeployedProcess(Request $request): JsonResponse + { + try { + return $this->deployFromRequest($request); + } catch (Throwable $exception) { + return $this->deployProcessFailureResponse($exception); + } + } + + private function deployFromRequest(Request $request): JsonResponse + { + $bpmn = $this->references->resolveNamedReferences($request->input('bpmn')); + $xmlErrors = $this->validateXml($bpmn); + if ($xmlErrors !== []) { + return response()->json([ + 'success' => false, + 'message' => 'Invalid BPMN XML.', + 'errors' => ['bpmn' => $xmlErrors], + ], 422); + } + + if ($this->targetsAlternativeB($request)) { + return $this->saveDeployedAlternativeB($request, $bpmn); + } + + [$process, $created] = $this->upsertProcessByName($request, $bpmn); + + return response()->json([ + 'success' => true, + 'action' => $created ? 'created' : 'updated', + 'process_id' => $process->id, + 'name' => $process->name, + ]); + } + + private function targetsAlternativeB(Request $request): bool + { + return $request->input('alternative') === 'B'; + } + + private function saveDeployedAlternativeB(Request $request, string $bpmn): JsonResponse + { + $process = Process::where('name', $request->input('name'))->first(); + $publish = $request->boolean('publish'); + $result = $this->alternativeB->deploy($process, $bpmn, $publish); + + return response()->json([ + 'success' => true, + 'action' => $publish ? 'published' : 'draft', + 'alternative' => 'B', + 'process_id' => $process->id, + 'name' => $process->name, + 'process_version_id' => $result['version_id'], + ]); + } + + /** + * @return array{0: Process, 1: bool} + */ + private function upsertProcessByName(Request $request, string $bpmn): array + { + return DB::transaction(function () use ($request, $bpmn): array { + $process = Process::where('name', $request->input('name'))->first(); + $created = $process === null; + + if ($created) { + $process = new Process(); + $process->name = $request->input('name'); + $process->description = $this->nonEmptyDescription( + $request->input('description'), + (string) $request->input('name'), + ); + $process->status = 'ACTIVE'; + $process->user_id = $request->user()->id; + $categoryId = $this->categories->resolveProcessCategoryId( + $request->input('process_category_name') + ); + if ($categoryId !== null) { + $process->process_category_id = $categoryId; + } + } elseif ($request->has('description')) { + $process->description = $this->nonEmptyDescription( + $request->input('description'), + (string) $process->name, + ); + } + + if (!$created && $request->has('process_category_name')) { + $categoryId = $this->categories->resolveProcessCategoryId( + $request->input('process_category_name') + ); + if ($categoryId !== null) { + $process->process_category_id = $categoryId; + } + } + + $process->bpmn = $bpmn; + $publishedVersionIdBefore = $this->latestPublishedVersionId($process); + $process->saveOrFail(); + + $this->applyDeployVersionName($process, $request, !$created, $publishedVersionIdBefore); + + return [$process->refresh(), $created]; + }); + } + + private function deployProcessFailureResponse(Throwable $exception): JsonResponse + { + if ($exception instanceof ValidationException) { + return response()->json([ + 'success' => false, + 'message' => collect($exception->errors())->flatten()->first(), + 'errors' => $exception->errors(), + ], 422); + } + + if ($exception instanceof MissingBpmnReferenceException) { + return response()->json([ + 'success' => false, + 'message' => $exception->getMessage(), + ], 422); + } + + report($exception); + + return response()->json([ + 'success' => false, + 'message' => 'The process could not be saved.', + 'error' => $exception->getMessage(), + ], 422); + } + + public function getProcessBpmn(Request $request): JsonResponse + { + $validator = Validator::make($request->all(), [ + 'name' => 'required|string|max:255', + ]); + + if ($validator->fails()) { + return response()->json([ + 'success' => false, + 'errors' => $validator->errors(), + ], 422); + } + + $process = Process::where('name', $request->input('name'))->first(); + if ($process === null) { + return response()->json([ + 'success' => false, + 'message' => 'Process not found.', + 'name' => $request->input('name'), + ], 404); + } + + return response()->json([ + 'success' => true, + 'process_id' => $process->id, + 'name' => $process->name, + 'bpmn' => $this->references->restoreNamedReferences((string) $process->bpmn), + ]); + } + + /** + * @return list + */ + private function validateXml(string $bpmn): array + { + $previous = libxml_use_internal_errors(true); + libxml_clear_errors(); + + $document = new DOMDocument(); + $valid = $document->loadXML($bpmn, LIBXML_NONET); + $errors = array_map( + static fn (\LibXMLError $error): string => trim($error->message), + libxml_get_errors() + ); + + libxml_clear_errors(); + libxml_use_internal_errors($previous); + + return $valid ? [] : $errors; + } + + private function nonEmptyDescription(mixed $description, string $fallbackName): string + { + if (is_string($description) && trim($description) !== '') { + return trim($description); + } + + return 'Process: ' . trim($fallbackName); + } +} diff --git a/ProcessMaker/Http/Controllers/Api/DeployScreen.php b/ProcessMaker/Http/Controllers/Api/DeployScreen.php new file mode 100644 index 0000000000..dd3ea90ce0 --- /dev/null +++ b/ProcessMaker/Http/Controllers/Api/DeployScreen.php @@ -0,0 +1,355 @@ +input('name'); + $isUpdate = Screen::where('title', $name)->exists(); + + if ($unavailable = $this->ensureDeployVersionHistoryAvailable($isUpdate)) { + return $unavailable; + } + + $validator = Validator::make( + $request->all(), + $this->deployRulesForUpdate([ + 'yml_content' => 'required|string', + 'name' => 'required|string', + ], $isUpdate), + ); + + if ($validator->fails()) { + return response()->json([ + 'success' => false, + 'errors' => $validator->errors(), + ], 422); + } + + return $this->persistDeployedScreen($request, $name); + } + + private function persistDeployedScreen(Request $request, string $name): JsonResponse + { + $ymlContent = $request->input('yml_content'); + $parsedData = $this->parseDeployYaml($ymlContent); + if ($parsedData instanceof JsonResponse) { + return $parsedData; + } + + $screen = Screen::where('title', $name)->first(); + $created = $screen === null; + + if ($created) { + $screen = new Screen(); + $screen->title = $name; + $screen->description = $this->screenDescription($parsedData, $name); + $screen->type = $parsedData['type'] ?? 'FORM'; + } elseif (array_key_exists('description', $parsedData)) { + $screen->description = $this->screenDescription($parsedData, $name); + } + + $categoryName = $parsedData['category'] ?? $parsedData['screen_category_name'] ?? null; + if ($created || $categoryName !== null) { + $categoryId = $this->categories->resolveScreenCategoryId( + is_string($categoryName) ? $categoryName : null + ); + if ($categoryId !== null) { + $screen->screen_category_id = (string) $categoryId; + } + } + + $this->applyYamlFields($screen, $parsedData, $created); + $publishedVersionIdBefore = $this->latestPublishedVersionId($screen); + $screen->save(); + $this->applyDeployVersionName($screen, $request, !$created, $publishedVersionIdBefore); + $screen->refresh(); + + return response()->json([ + 'success' => true, + 'action' => $created ? 'created' : 'updated', + 'screen_id' => $screen->id, + 'name' => $screen->title, + 'message' => $created + ? 'Screen created from YAML.' + : 'Screen updated from YAML.', + ]); + } + + /** + * @return \Illuminate\Http\Response|JsonResponse + */ + public function getScreenYaml(Request $request) + { + $validator = Validator::make($request->all(), [ + 'name' => 'required|string', + ]); + + if ($validator->fails()) { + return response()->json([ + 'success' => false, + 'errors' => $validator->errors(), + ], 422); + } + + $name = $request->input('name'); + $resolved = $this->resolvePublishedScreenByTitle($name); + if ($resolved instanceof JsonResponse) { + return $resolved; + } + + [$screen, $screenVersion] = $resolved; + $config = $this->withEmptyInspector($this->removeInspectorMetadata($screenVersion->config ?? [])); + $data = [ + 'config' => $config, + 'computed' => $screenVersion->computed, + 'watchers' => $screenVersion->watchers, + 'custom_css' => $screenVersion->custom_css, + 'preview_presets' => $screenVersion->preview_presets ?? [], + ]; + $yaml = Yaml::dump($data, 100, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK); + + return response($yaml, 200) + ->header('Content-Type', 'text/yaml') + ->header('X-Screen-Id', (string) $screen->id) + ->header('X-Screen-Name', $screen->title); + } + + /** + * The export drops the (large) inspector metadata, but the YAML contract expects every + * item to carry `inspector: []`, so a pulled screen can be pushed back unchanged. + * + * @param array $config + * @return array + */ + private function withEmptyInspector(array $config): array + { + foreach ($config as $index => $page) { + if (is_array($page) && isset($page['items']) && is_array($page['items'])) { + $config[$index]['items'] = $this->addEmptyInspector($page['items']); + } + } + + return $config; + } + + /** + * @param array $items + * @return array + */ + private function addEmptyInspector(array $items): array + { + foreach ($items as $index => $item) { + if (!is_array($item)) { + continue; + } + if (isset($item['component']) && !array_key_exists('inspector', $item)) { + $item['inspector'] = []; + } + if (isset($item['items']) && is_array($item['items'])) { + $item['items'] = $this->addEmptyInspector($item['items']); + } + // A FormMultiColumn holds a list of columns, and each column is a list of items. + $items[$index] = array_is_list($item) && $item !== [] ? $this->addEmptyInspector($item) : $item; + } + + return $items; + } + + /** + * @return array{0: Screen, 1: object}|JsonResponse + */ + private function resolvePublishedScreenByTitle(string $name): array|JsonResponse + { + $screen = Screen::where('title', $name)->first(); + if ($screen === null) { + return response()->json([ + 'success' => false, + 'message' => 'Screen not found', + 'name' => $name, + ], 404); + } + + $screenVersion = $screen->getPublishedVersion([]); + if ($screenVersion === null) { + return response()->json([ + 'success' => false, + 'message' => 'Screen does not have a published version', + 'name' => $name, + 'screen_id' => $screen->id, + ], 404); + } + + return [$screen, $screenVersion]; + } + + /** + * @return array|JsonResponse + */ + private function parseDeployYaml(string $ymlContent): array|JsonResponse + { + try { + $parsedData = Yaml::parse($ymlContent) ?? []; + } catch (\Exception $e) { + return response()->json([ + 'success' => false, + 'message' => 'Invalid YAML content', + 'error' => $e->getMessage(), + ], 400); + } + + if (!is_array($parsedData)) { + return response()->json([ + 'success' => false, + 'message' => 'Invalid YAML content', + 'error' => 'YAML must parse to a mapping of screen fields', + ], 400); + } + + return $parsedData; + } + + private function applyYamlFields(Screen $screen, array $parsedData, bool $created): void + { + if (array_key_exists('preview_presets', $parsedData)) { + $parsedData['preview_presets'] = $this->normalizePreviewPresets($parsedData['preview_presets']); + } + + $defaults = [ + 'config' => [], + 'computed' => [], + 'watchers' => [], + 'custom_css' => '', + 'preview_presets' => [], + ]; + + foreach ($defaults as $field => $default) { + if (array_key_exists($field, $parsedData)) { + $screen->{$field} = $parsedData[$field]; + } elseif ($created) { + $screen->{$field} = $default; + } + } + } + + /** + * Designer stores each preset data value as a JSON string so `{}` survives decode. + * + * @return list + */ + private function normalizePreviewPresets(mixed $presets): array + { + if (!is_array($presets)) { + return []; + } + + $normalized = []; + foreach ($presets as $preset) { + if (!is_array($preset)) { + continue; + } + $title = $preset['title'] ?? ''; + $normalized[] = [ + 'title' => is_string($title) ? $title : '', + 'data' => $this->encodePresetData($preset['data'] ?? self::EMPTY_PRESET_DATA), + ]; + } + + return $normalized; + } + + private function encodePresetData(mixed $data): string + { + if (is_array($data)) { + // YAML empty mappings parse as []; json_encode would persist them as []. + $encoded = json_encode( + $this->emptyMapsToObjects($data), + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES + ); + + return $encoded === false ? self::EMPTY_PRESET_DATA : $encoded; + } + + if (is_string($data) && $this->isJsonString($data)) { + return $data; + } + + return self::EMPTY_PRESET_DATA; + } + + /** + * Recursively turn empty arrays into objects so preview data keeps {}. + * shortcut: empty YAML sequences under a key also become {}, revisit if presets need [] leaves + */ + private function emptyMapsToObjects(array $data): array|\stdClass + { + if ($data === []) { + return new \stdClass(); + } + + foreach ($data as $key => $value) { + if (is_array($value)) { + $data[$key] = $this->emptyMapsToObjects($value); + } + } + + return $data; + } + + private function isJsonString(string $data): bool + { + try { + json_decode($data, true, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException) { + return false; + } + + return true; + } + + /** + * @param array $parsedData + */ + private function screenDescription(array $parsedData, string $title): string + { + $description = $parsedData['description'] ?? ''; + if (is_string($description) && trim($description) !== '') { + return trim($description); + } + + return 'Screen: ' . trim($title); + } +} diff --git a/ProcessMaker/Http/Controllers/Api/DeployScript.php b/ProcessMaker/Http/Controllers/Api/DeployScript.php new file mode 100644 index 0000000000..655940d9a7 --- /dev/null +++ b/ProcessMaker/Http/Controllers/Api/DeployScript.php @@ -0,0 +1,285 @@ +input('name'); + $isUpdate = Script::where('title', $name)->exists(); + + $rejection = $this->rejectDeployRequest($request, $name, $isUpdate); + + return $rejection ?? $this->persistDeployedScript($request, $name); + } + + /** + * Return the response that stops a deploy (version history unavailable, + * validation failure, or forbidden executor binding), or null to proceed. + */ + private function rejectDeployRequest(Request $request, string $name, bool $isUpdate): ?JsonResponse + { + if ($unavailable = $this->ensureDeployVersionHistoryAvailable($isUpdate)) { + return $unavailable; + } + + $validator = Validator::make( + $request->all(), + $this->deployRulesForUpdate([ + 'code' => 'required|string', + 'name' => 'required|string', + 'description' => 'nullable|string|max:65535', + 'script_category_name' => 'nullable|string|max:255', + 'script_executor_id' => 'nullable|integer', + 'script_executor_title' => 'nullable|string|max:255', + ], $isUpdate), + ); + $validator->after(fn ($validator) => $this->validateRequestedExecutor($request, $validator)); + + if ($validator->fails()) { + return response()->json([ + 'success' => false, + 'errors' => $validator->errors(), + ], 422); + } + + return $this->denyUnauthorizedExecutorBinding($request, $name); + } + + /** + * Binding a script to an executor needs the same rights as the regular script + * routes: edit-scripts, and an administrator for any executor other than the + * default one (or any custom executor). Requests that name no executor, and + * requests that keep the executor a script already has, are not restricted. + */ + private function denyUnauthorizedExecutorBinding(Request $request, string $name): ?JsonResponse + { + $requested = $this->requestedExecutor($request); + $message = $requested === null + ? null + : $this->executorBindingDenialMessage($request->user(), $requested, $name); + + if ($message === null) { + return null; + } + + return response()->json([ + 'success' => false, + 'message' => $message, + ], 403); + } + + /** + * Return why the user may not bind the script to the requested executor, + * or null when the binding is allowed. + */ + private function executorBindingDenialMessage(User $user, ScriptExecutor $requested, string $name): ?string + { + if ($user->is_administrator || $this->keepsCurrentExecutor($name, $requested)) { + return null; + } + + if (!$user->can('edit-scripts')) { + return 'You are not allowed to choose a script executor.'; + } + + return $this->executors->isDefaultForNonAdmins($requested) + ? null + : 'Only administrators can use this script executor.'; + } + + private function keepsCurrentExecutor(string $name, ScriptExecutor $requested): bool + { + $current = Script::where('title', $name)->value('script_executor_id'); + + return $current !== null && (int) $current === $requested->id; + } + + private function requestedExecutor(Request $request): ?ScriptExecutor + { + $id = $request->input('script_executor_id'); + + return $this->executors->findRequested( + $id === null || $id === '' ? null : (int) $id, + $request->input('script_executor_title'), + ); + } + + private function validateRequestedExecutor(Request $request, \Illuminate\Validation\Validator $validator): void + { + $field = $request->filled('script_executor_id') ? 'script_executor_id' : 'script_executor_title'; + if (!$request->filled($field)) { + return; + } + + $executor = $this->requestedExecutor($request); + if ($executor === null) { + $validator->errors()->add($field, 'The selected script executor does not exist.'); + + return; + } + if ($executor->language !== ScriptExecutorResolver::DEPLOY_LANGUAGE) { + $validator->errors()->add($field, sprintf( + 'Script executor "%s" runs %s; deploy-script needs a %s executor.', + $executor->title, + $executor->language, + ScriptExecutorResolver::DEPLOY_LANGUAGE, + )); + } + } + + private function persistDeployedScript(Request $request, string $name): JsonResponse + { + $code = $request->input('code'); + $script = Script::where('title', $name)->first(); + $created = $script === null; + $requestedExecutor = $this->requestedExecutor($request); + + if ($created) { + $executor = $requestedExecutor ?? $this->executors->resolveForNewScript(); + if ($executor === null) { + return response()->json([ + 'success' => false, + 'message' => 'No script executor is available to create a script.', + ], 422); + } + + $script = new Script(); + $script->title = $name; + $script->description = $this->deployScriptDescription($request, $name); + $script->language = $executor->language; + $script->script_executor_id = $executor->id; + $script->run_as_user_id = $request->user()->id; + $script->timeout = self::DEFAULT_TIMEOUT; + $script->retry_attempts = self::DEFAULT_RETRY_ATTEMPTS; + $script->retry_wait_time = self::DEFAULT_RETRY_WAIT_TIME; + } + + if (!$created && $requestedExecutor !== null) { + $script->script_executor_id = $requestedExecutor->id; + $script->language = $requestedExecutor->language; + } + + if (!$created && $request->has('description')) { + $script->description = $this->deployScriptDescription($request, $name); + } + + if ($created || $request->has('script_category_name')) { + $categoryId = $this->categories->resolveScriptCategoryId( + $request->input('script_category_name') + ); + if ($categoryId !== null) { + $script->script_category_id = (string) $categoryId; + } + } + + $script->code = $code; + $publishedVersionIdBefore = $this->latestPublishedVersionId($script); + $script->save(); + $this->applyDeployVersionName($script, $request, !$created, $publishedVersionIdBefore); + $script->refresh(); + + return response()->json([ + 'success' => true, + 'action' => $created ? 'created' : 'updated', + 'script_id' => $script->id, + 'name' => $script->title, + 'message' => $created + ? 'Script created from PHP.' + : 'Script updated from PHP.', + ]); + } + + /** + * Return the published script PHP source, looked up by title. + * + * @return \Illuminate\Http\Response|JsonResponse + */ + public function getScriptPhp(Request $request) + { + $validator = Validator::make($request->all(), [ + 'name' => 'required|string', + ]); + + if ($validator->fails()) { + return response()->json([ + 'success' => false, + 'errors' => $validator->errors(), + ], 422); + } + + $name = $request->input('name'); + $script = Script::where('title', $name)->first(); + $scriptVersion = $script?->getPublishedVersion([]); + if ($script === null || $scriptVersion === null) { + $payload = [ + 'success' => false, + 'message' => $script === null + ? 'Script not found' + : 'Script does not have a published version', + 'name' => $name, + ]; + if ($script !== null) { + $payload['script_id'] = $script->id; + } + + return response()->json($payload, 404); + } + + return response((string) ($scriptVersion->code ?? ''), 200) + ->header('Content-Type', 'text/plain; charset=UTF-8') + ->header('X-Script-Id', (string) $script->id) + ->header('X-Script-Name', $script->title); + } + + private function deployScriptDescription(Request $request, string $title): string + { + $description = $request->input('description'); + if (is_string($description) && trim($description) !== '') { + return trim($description); + } + + return 'Script: ' . trim($title); + } +} diff --git a/ProcessMaker/Http/Controllers/Api/GroupMemberController.php b/ProcessMaker/Http/Controllers/Api/GroupMemberController.php index b5b95207f1..face7d9e48 100644 --- a/ProcessMaker/Http/Controllers/Api/GroupMemberController.php +++ b/ProcessMaker/Http/Controllers/Api/GroupMemberController.php @@ -214,7 +214,7 @@ public function destroy(GroupMember $group_member) /** * Display a listing of groups available * - * @param \Illuminate\Http\Request $request + * @param Request $request * @return ApiCollection * * @OA\Get( @@ -338,7 +338,7 @@ public function groupsAvailable(Request $request) /** * Display a listing of users available * - * @param \Illuminate\Http\Request $request + * @param Request $request * @return ApiCollection * * @OA\Get( diff --git a/ProcessMaker/Http/Controllers/Api/ImportController.php b/ProcessMaker/Http/Controllers/Api/ImportController.php index e008bf2e1c..a6c598afa0 100644 --- a/ProcessMaker/Http/Controllers/Api/ImportController.php +++ b/ProcessMaker/Http/Controllers/Api/ImportController.php @@ -41,7 +41,7 @@ public function preview(Request $request, $version = null): JsonResponse return response()->json(['error' => $e->getMessage()], 400); } - $options = new Options([]); + $options = new Options([], $request->user()?->id); $importer = new Importer($payload, $options); $manifest = $importer->previewImport(); @@ -80,7 +80,10 @@ public function import(Request $request): JsonResponse return response()->json(['error' => $e->getMessage()], 400); } - $options = new Options(json_decode(file_get_contents(utf8_decode($request->file('options'))), true)); + $options = new Options( + json_decode(file_get_contents(utf8_decode($request->file('options'))), true), + $request->user()?->id + ); $importer = new Importer($payload, $options); $manifest = $importer->doImport(); diff --git a/ProcessMaker/Http/Controllers/Api/PluginController.php b/ProcessMaker/Http/Controllers/Api/PluginController.php new file mode 100644 index 0000000000..f9caa26466 --- /dev/null +++ b/ProcessMaker/Http/Controllers/Api/PluginController.php @@ -0,0 +1,110 @@ +manager->list(); + + return response()->json(['data' => $plugins]); + } + + public function install(Request $request): JsonResponse + { + $maxZipKilobytes = (int) config('plugin_manager.zip_max_kilobytes', 51200); + + $request->validate([ + 'url' => 'required_without:zip|nullable|string' . (config('app.env') === 'production' ? '|starts_with:https://' : ''), + 'zip' => "required_without:url|nullable|file|mimes:zip|max:{$maxZipKilobytes}", + 'branch' => 'prohibits:tag|nullable|string', + 'tag' => 'prohibits:branch|nullable|string', + 'git_username' => 'nullable|string|max:255', + 'git_token' => 'nullable|string|max:4096', + ]); + + $userId = $request->user()->id; + + if ($request->hasFile('zip')) { + $tmpPath = $request->file('zip')->store('plugin-uploads', 'local'); + $fullPath = storage_path('app/' . $tmpPath); + + InstallPlugin::dispatch( + userId: $userId, + zipPath: $fullPath, + ); + } else { + InstallPlugin::dispatch( + userId: $userId, + url: $request->input('url'), + branch: $request->input('branch'), + tag: $request->input('tag'), + gitUsername: $request->input('git_username'), + gitToken: $request->input('git_token'), + ); + } + + return response()->json([ + 'queued' => true, + 'message' => 'Plugin installation queued', + ]); + } + + public function reinstall(string $name, Request $request): JsonResponse + { + $request->validate([ + 'branch' => 'prohibits:tag|nullable|string', + 'tag' => 'prohibits:branch|nullable|string', + 'git_username' => 'nullable|string|max:255', + 'git_token' => 'nullable|string|max:4096', + ]); + + ReinstallPlugin::dispatch( + $name, + $request->user()->id, + $request->input('branch'), + $request->input('tag'), + $request->input('git_username'), + $request->input('git_token'), + ); + + return response()->json([ + 'queued' => true, + 'message' => 'Plugin reinstall queued', + ]); + } + + public function destroy(string $name, Request $request): JsonResponse + { + UninstallPlugin::dispatch($name, $request->user()->id); + + return response()->json([ + 'queued' => true, + 'message' => 'Plugin uninstallation queued', + ]); + } + + public function toggle(string $name, Request $request): JsonResponse + { + TogglePlugin::dispatch($name, $request->user()->id); + + return response()->json([ + 'queued' => true, + 'message' => 'Plugin toggle queued', + ]); + } +} diff --git a/ProcessMaker/Http/Controllers/Api/ScriptController.php b/ProcessMaker/Http/Controllers/Api/ScriptController.php index e3cca93814..7fa45f84f7 100644 --- a/ProcessMaker/Http/Controllers/Api/ScriptController.php +++ b/ProcessMaker/Http/Controllers/Api/ScriptController.php @@ -173,6 +173,11 @@ public function index(Request $request) * property="nonce", * type="string", * ), + * @OA\Property( + * property="run_in_process", + * type="boolean", + * description="When true (and Core Service Task enabled), preview via in-process PHP runner instead of Docker/microservice. Also auto-enabled when the script has allow_in_process=true.", + * ), * ), * ), * @@ -189,10 +194,27 @@ public function preview(Request $request, Script $script) $config = $this->getRequestArray($request->get('config')); $code = $request->get('code'); $nonce = $request->get('nonce'); + $runInProcess = $this->shouldPreviewInProcess($request, $script); + + TestScript::dispatch($script, $request->user(), $code, $data, $config, $nonce, $runInProcess)->onQueue('bpmn'); + + return ['status' => 'success', 'run_in_process' => $runInProcess]; + } + + /** + * Decide if script preview should use Core Service Task in-process runner. + */ + private function shouldPreviewInProcess(Request $request, Script $script): bool + { + if (!config('core-service-task.enabled') || strtolower((string) $script->language) !== 'php') { + return false; + } - TestScript::dispatch($script, $request->user(), $code, $data, $config, $nonce)->onQueue('bpmn'); + if ($request->boolean('run_in_process')) { + return true; + } - return ['status' => 'success']; + return (bool) $script->allow_in_process; } /** @@ -347,6 +369,7 @@ public function show(Script $script) */ public function store(Request $request) { + $this->authorizeModulesExecution($request); $request->validate(Script::rules()); $script = new Script(); $script->fill($request->input()); @@ -399,6 +422,7 @@ public function store(Request $request) */ public function update(Script $script, Request $request) { + $this->authorizeModulesExecution($request, $script); $request->validate(Script::rules($script)); $script->fill($request->input()); $original = array_intersect_key($script->getOriginal(), $script->getDirty()); @@ -415,6 +439,20 @@ public function update(Script $script, Request $request) return response($request, 204); } + private function authorizeModulesExecution(Request $request, ?Script $script = null): void + { + $executionMode = $request->input('execution_mode', $script?->execution_mode); + if ($executionMode !== Script::EXECUTION_MODE_MODULES) { + return; + } + + if ($this->canUseModules($request)) { + return; + } + + $request->merge(['execution_mode' => Script::EXECUTION_MODE_BARE]); + } + /** * Update a draft script. * @@ -492,6 +530,7 @@ public function draft(Script $script, Request $request) */ public function duplicate(Script $script, Request $request) { + $this->authorizeModulesExecution($request, $script); $request->validate(Script::rules()); $newScript = new Script(); @@ -510,12 +549,27 @@ public function duplicate(Script $script, Request $request) $newScript->description = $request->input('description'); } + $newScript->execution_mode = $request->input( + 'execution_mode', + $script->execution_mode === Script::EXECUTION_MODE_MODULES + && $this->canUseModules($request) + ? Script::EXECUTION_MODE_MODULES + : Script::EXECUTION_MODE_BARE + ); $newScript->saveOrFail(); ScriptDuplicated::dispatch($newScript, $newScript->getChanges()); return new ScriptResource($newScript); } + private function canUseModules(Request $request): bool + { + return (bool) ( + $request->user()?->is_administrator + || $request->user()?->can('run-in-process-modules') + ); + } + /** * Delete a script in a process. * diff --git a/ProcessMaker/Http/Controllers/Api/SignalController.php b/ProcessMaker/Http/Controllers/Api/SignalController.php index b4432e8fa0..798b642838 100644 --- a/ProcessMaker/Http/Controllers/Api/SignalController.php +++ b/ProcessMaker/Http/Controllers/Api/SignalController.php @@ -24,7 +24,7 @@ class SignalController extends Controller * * @param Request $request * - * @return \Illuminate\Http\Response + * @return Response * * @OA\Get( * path="/signals", diff --git a/ProcessMaker/Http/Controllers/Process/ScreenBuilderController.php b/ProcessMaker/Http/Controllers/Process/ScreenBuilderController.php index 76727289ef..5e9aa2c40f 100644 --- a/ProcessMaker/Http/Controllers/Process/ScreenBuilderController.php +++ b/ProcessMaker/Http/Controllers/Process/ScreenBuilderController.php @@ -36,6 +36,7 @@ public function edit(ScreenBuilderManager $manager, Screen $screen, $processId = 'computed', 'custom_css', 'watchers', + 'preview_presets', ])); } diff --git a/ProcessMaker/Http/Controllers/Process/ScreenController.php b/ProcessMaker/Http/Controllers/Process/ScreenController.php index 65ba86dbb3..182a130400 100644 --- a/ProcessMaker/Http/Controllers/Process/ScreenController.php +++ b/ProcessMaker/Http/Controllers/Process/ScreenController.php @@ -83,7 +83,7 @@ public function edit(Screen $screen) { $addons = $this->getPluginAddons('edit', compact(['screen'])); $assignedProjects = json_decode($screen->projects, true); - + $lastDraftOrPublishedVersion = $screen->getDraftOrPublishedLatestVersion(); $isDraft = 0; @@ -92,11 +92,11 @@ public function edit(Screen $screen) } return view('processes.screens.edit', compact( - 'screen', - 'addons', - 'assignedProjects', - 'isDraft' - ) + 'screen', + 'addons', + 'assignedProjects', + 'isDraft' + ) ); } diff --git a/ProcessMaker/Http/Controllers/Process/SignalController.php b/ProcessMaker/Http/Controllers/Process/SignalController.php index d248e832b3..a632bc7561 100644 --- a/ProcessMaker/Http/Controllers/Process/SignalController.php +++ b/ProcessMaker/Http/Controllers/Process/SignalController.php @@ -28,7 +28,7 @@ public function index(Request $request) /** * Get a specific signal * - * @return \Illuminate\View\View|\Illuminate\Contracts\View + * @return View|\Illuminate\Contracts\View */ public function edit($id) { diff --git a/ProcessMaker/Http/Middleware/GenerateMenus.php b/ProcessMaker/Http/Middleware/GenerateMenus.php index f60536d283..caf1cf5e7b 100644 --- a/ProcessMaker/Http/Middleware/GenerateMenus.php +++ b/ProcessMaker/Http/Middleware/GenerateMenus.php @@ -122,6 +122,10 @@ public function handle(Request $request, Closure $next) 'icon' => 'fa-code', ]); } + $submenu->add(__('Plugins'), [ + 'route' => 'plugins.index', + 'icon' => 'fa-plug', + ]); if (config('app.case_retention_policy_enabled')) { $submenu->add(__('Cases Retention Logs'), [ diff --git a/ProcessMaker/Http/Middleware/IgnoreMapFiles.php b/ProcessMaker/Http/Middleware/IgnoreMapFiles.php index 46ed2eaee0..1fdeab0388 100644 --- a/ProcessMaker/Http/Middleware/IgnoreMapFiles.php +++ b/ProcessMaker/Http/Middleware/IgnoreMapFiles.php @@ -10,7 +10,7 @@ class IgnoreMapFiles * Handle an incoming request. * * @param \Illuminate\Http\Request $request - * @param \Closure $next + * @param Closure $next * @return mixed */ public function handle($request, Closure $next) diff --git a/ProcessMaker/Http/Middleware/IsAdmin.php b/ProcessMaker/Http/Middleware/IsAdmin.php index 232347f356..5e52f70156 100644 --- a/ProcessMaker/Http/Middleware/IsAdmin.php +++ b/ProcessMaker/Http/Middleware/IsAdmin.php @@ -11,7 +11,7 @@ class IsAdmin /** * Handle an incoming request. * - * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next + * @param Closure(Request): (Response) $next */ public function handle(Request $request, Closure $next): Response { diff --git a/ProcessMaker/Http/Middleware/NoCache.php b/ProcessMaker/Http/Middleware/NoCache.php index d85df5ff3b..ca7694ecbf 100644 --- a/ProcessMaker/Http/Middleware/NoCache.php +++ b/ProcessMaker/Http/Middleware/NoCache.php @@ -11,7 +11,7 @@ class NoCache /** * Handle an incoming request. * - * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next + * @param Closure(Request): (Response) $next */ public function handle(Request $request, Closure $next): Response { diff --git a/ProcessMaker/Http/Middleware/PermissionCheck.php b/ProcessMaker/Http/Middleware/PermissionCheck.php index 8b55c9348b..40d2154ac0 100644 --- a/ProcessMaker/Http/Middleware/PermissionCheck.php +++ b/ProcessMaker/Http/Middleware/PermissionCheck.php @@ -14,22 +14,22 @@ class PermissionCheck /** * The authentication factory instance. * - * @var \Illuminate\Contracts\Auth\Factory + * @var Auth */ protected $auth; /** * The gate instance. * - * @var \Illuminate\Contracts\Auth\Access\Gate + * @var Gate */ protected $gate; /** * Create a new middleware instance. * - * @param \Illuminate\Contracts\Auth\Factory $auth - * @param \Illuminate\Contracts\Auth\Access\Gate $gate + * @param Auth $auth + * @param Gate $gate * @return void */ public function __construct(Auth $auth, Gate $gate) @@ -42,7 +42,7 @@ public function __construct(Auth $auth, Gate $gate) * Handle an incoming request. * * @param \Illuminate\Http\Request $request - * @param \Closure $next + * @param Closure $next * @param string $ability * @param array|null $models * @return mixed diff --git a/ProcessMaker/Http/Middleware/RedirectIfAuthenticated.php b/ProcessMaker/Http/Middleware/RedirectIfAuthenticated.php index 390d42bbd5..e80eae30ea 100644 --- a/ProcessMaker/Http/Middleware/RedirectIfAuthenticated.php +++ b/ProcessMaker/Http/Middleware/RedirectIfAuthenticated.php @@ -11,7 +11,7 @@ class RedirectIfAuthenticated * Handle an incoming request. * * @param \Illuminate\Http\Request $request - * @param \Closure $next + * @param Closure $next * @param string|null $guard * @return mixed */ diff --git a/ProcessMaker/Http/Middleware/SamlRequest.php b/ProcessMaker/Http/Middleware/SamlRequest.php index 1ab1b40740..65f3ecb763 100644 --- a/ProcessMaker/Http/Middleware/SamlRequest.php +++ b/ProcessMaker/Http/Middleware/SamlRequest.php @@ -12,7 +12,7 @@ class SamlRequest /** * Handle an incoming request. * - * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next + * @param Closure(Request): (Response) $next */ public function handle(Request $request, Closure $next): Response { diff --git a/ProcessMaker/Http/Middleware/ServerTimingMiddleware.php b/ProcessMaker/Http/Middleware/ServerTimingMiddleware.php index 2a15e84a6d..f0be97d658 100644 --- a/ProcessMaker/Http/Middleware/ServerTimingMiddleware.php +++ b/ProcessMaker/Http/Middleware/ServerTimingMiddleware.php @@ -20,7 +20,7 @@ public function __construct() /** * Handle an incoming request. * - * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next + * @param Closure(Request): (Response) $next */ public function handle(Request $request, Closure $next): Response { diff --git a/ProcessMaker/Http/Middleware/SessionControlBlock.php b/ProcessMaker/Http/Middleware/SessionControlBlock.php index 40cc8d9b7c..94d8ad7782 100644 --- a/ProcessMaker/Http/Middleware/SessionControlBlock.php +++ b/ProcessMaker/Http/Middleware/SessionControlBlock.php @@ -21,7 +21,7 @@ class SessionControlBlock /** * Handle an incoming request. * - * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next + * @param Closure(Request): (Response) $next */ public function handle(Request $request, Closure $next): Response { diff --git a/ProcessMaker/Http/Middleware/SessionControlKill.php b/ProcessMaker/Http/Middleware/SessionControlKill.php index 30646faf1b..687d8b3082 100644 --- a/ProcessMaker/Http/Middleware/SessionControlKill.php +++ b/ProcessMaker/Http/Middleware/SessionControlKill.php @@ -21,7 +21,7 @@ class SessionControlKill /** * Handle an incoming request. * - * @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next + * @param Closure(Request): (Response) $next */ public function handle(Request $request, Closure $next): Response { diff --git a/ProcessMaker/Http/Middleware/TrustHosts.php b/ProcessMaker/Http/Middleware/TrustHosts.php index 64cce31bd4..e0aab77236 100644 --- a/ProcessMaker/Http/Middleware/TrustHosts.php +++ b/ProcessMaker/Http/Middleware/TrustHosts.php @@ -56,6 +56,7 @@ public function handle(Request $request, $next) if (!$trusted) { \Log::warning('Rejected request with untrusted X-Forwarded-Host', [ 'forwarded_host' => $forwardedHost, + 'trusted_pattern' => $this->hosts(), ]); abort(400, 'Invalid Host Header'); } diff --git a/ProcessMaker/Http/Middleware/TwoFactorAuthentication.php b/ProcessMaker/Http/Middleware/TwoFactorAuthentication.php index 2dd7f74042..ca9fa124b8 100644 --- a/ProcessMaker/Http/Middleware/TwoFactorAuthentication.php +++ b/ProcessMaker/Http/Middleware/TwoFactorAuthentication.php @@ -11,7 +11,7 @@ class TwoFactorAuthentication * Handle an incoming request. * * @param \Illuminate\Http\Request $request - * @param \Closure $next + * @param Closure $next * @return mixed */ public function handle($request, Closure $next) diff --git a/ProcessMaker/Http/Resources/ApiCollection.php b/ProcessMaker/Http/Resources/ApiCollection.php index 07f3b7d529..c4b2a7788c 100644 --- a/ProcessMaker/Http/Resources/ApiCollection.php +++ b/ProcessMaker/Http/Resources/ApiCollection.php @@ -62,7 +62,7 @@ public function __construct($resource, $total = null) /** * Generic collection to add sorting and filtering metadata. * - * @param \Illuminate\Http\Request $request + * @param Request $request * @return array */ public function toArray($request) @@ -92,7 +92,7 @@ public function toArray($request) /** * Create an HTTP response that represents the object. * - * @param \Illuminate\Http\Request $request + * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function toResponse($request) @@ -109,9 +109,9 @@ public function toResponse($request) /** * Convert a Collection to a LengthAwarePaginator * - * @param \Illuminate\Support\Collection $collection - * @param \Illuminate\Http\Request $request - * @return \Illuminate\Pagination\LengthAwarePaginator + * @param Collection $collection + * @param Request $request + * @return LengthAwarePaginator */ public function collectionToPaginator(Collection $collection, Request $request) { diff --git a/ProcessMaker/ImportExport/Exporters/ScriptExporter.php b/ProcessMaker/ImportExport/Exporters/ScriptExporter.php index c1083bbca5..6fc731eace 100644 --- a/ProcessMaker/ImportExport/Exporters/ScriptExporter.php +++ b/ProcessMaker/ImportExport/Exporters/ScriptExporter.php @@ -6,6 +6,7 @@ use Illuminate\Support\Facades\Log; use ProcessMaker\ImportExport\DependentType; use ProcessMaker\Models\EnvironmentVariable; +use ProcessMaker\Models\Script; use ProcessMaker\Models\ScriptCategory; use ProcessMaker\Models\User; @@ -51,6 +52,13 @@ public function import() : bool // Update environment variable references in script code $this->updateEnvironmentVariableReferences(); + if ( + $this->model->execution_mode === Script::EXECUTION_MODE_MODULES + && !$this->canUseModules() + ) { + $this->model->execution_mode = Script::EXECUTION_MODE_BARE; + } + // Pre-save cleanup for data source scripts to prevent constraint violations if ($this->mode === 'update' && $this->model->exists) { // Check if this script has any data source relationships that might cause conflicts @@ -70,6 +78,15 @@ public function import() : bool return $this->model->save(); } + private function canUseModules(): bool + { + $user = $this->options->importingUserId + ? User::find($this->options->importingUserId) + : auth()->user(); + + return (bool) ($user?->is_administrator || $user?->can('run-in-process-modules')); + } + private function getEnvironmentVariables() : array { $environmentVariables = EnvironmentVariable::get(); diff --git a/ProcessMaker/Jobs/BoundaryEvent.php b/ProcessMaker/Jobs/BoundaryEvent.php index d5a56a7f0c..c42276a306 100644 --- a/ProcessMaker/Jobs/BoundaryEvent.php +++ b/ProcessMaker/Jobs/BoundaryEvent.php @@ -42,7 +42,7 @@ public function __construct(Definitions $definitions, ExecutionInstanceInterface * * @param TokenInterface $token * @param CatchEventInterface $element - * @return \ProcessMaker\Nayra\Contracts\Engine\ExecutionInstanceInterface + * @return ExecutionInstanceInterface */ public function action(BpmnDocumentInterface $definitions, TokenInterface $token = null) { diff --git a/ProcessMaker/Jobs/CatchEvent.php b/ProcessMaker/Jobs/CatchEvent.php index bd0aefd676..961580bbfc 100644 --- a/ProcessMaker/Jobs/CatchEvent.php +++ b/ProcessMaker/Jobs/CatchEvent.php @@ -37,7 +37,7 @@ public function __construct(Definitions $definitions, ExecutionInstanceInterface * * @param TokenInterface $token * @param CatchEventInterface $element - * @return \ProcessMaker\Nayra\Contracts\Engine\ExecutionInstanceInterface + * @return ExecutionInstanceInterface */ public function action(TokenInterface $token, CatchEventInterface $element) { diff --git a/ProcessMaker/Jobs/CatchSignalEventInRequest.php b/ProcessMaker/Jobs/CatchSignalEventInRequest.php index ca8c0c4f0b..f177113ee3 100644 --- a/ProcessMaker/Jobs/CatchSignalEventInRequest.php +++ b/ProcessMaker/Jobs/CatchSignalEventInRequest.php @@ -27,7 +27,7 @@ class CatchSignalEventInRequest extends BpmnAction implements ShouldQueue /** * Create a new job instance. * - * @param \ProcessMaker\Models\ProcessRequest $instance + * @param ProcessRequest $instance * @param array $data * @param string $signalRef */ diff --git a/ProcessMaker/Jobs/ExecuteScript.php b/ProcessMaker/Jobs/ExecuteScript.php index f82147a07c..e57eb6427f 100644 --- a/ProcessMaker/Jobs/ExecuteScript.php +++ b/ProcessMaker/Jobs/ExecuteScript.php @@ -115,6 +115,7 @@ public function handleNayraDocker() ]); $result = curl_exec($ch); curl_close($ch); + return $result; } diff --git a/ProcessMaker/Jobs/ImportProcess.php b/ProcessMaker/Jobs/ImportProcess.php index 03b4768916..1e31e763ae 100644 --- a/ProcessMaker/Jobs/ImportProcess.php +++ b/ProcessMaker/Jobs/ImportProcess.php @@ -518,6 +518,7 @@ protected function saveScreen($screen) return $new; } catch (\Exception $e) { Log::error('Import Screen: ' . $e->getMessage()); + return false; } } diff --git a/ProcessMaker/Jobs/ImportV2.php b/ProcessMaker/Jobs/ImportV2.php index 8937976082..ac857031bf 100644 --- a/ProcessMaker/Jobs/ImportV2.php +++ b/ProcessMaker/Jobs/ImportV2.php @@ -83,7 +83,7 @@ private function runImport($logger) return; } - $options = new Options($options); + $options = new Options($options, $this->userId); $importer = new Importer($payload, $options, $logger); if ($this->isPreview) { $manifest = $importer->previewImport(); diff --git a/ProcessMaker/Jobs/InstallPlugin.php b/ProcessMaker/Jobs/InstallPlugin.php new file mode 100644 index 0000000000..12d53f84c0 --- /dev/null +++ b/ProcessMaker/Jobs/InstallPlugin.php @@ -0,0 +1,90 @@ +releaseAfter(30) + ->expireAfter(630), + ]; + } + + public function handle(PluginManager $manager): void + { + try { + $label = $this->zipPath ? basename($this->zipPath) : ($this->url ?? 'plugin'); + event(new PluginLog('Starting queued plugin installation...', 'starting', $label, $this->userId)); + + if ($this->zipPath) { + $manager->installFromZip($this->zipPath, $this->userId); + + return; + } + + $manager->install( + $this->url, + $this->branch, + $this->tag, + $this->userId, + $this->gitUsername, + $this->gitToken + ); + } catch (Throwable $exception) { + $manager->revertFailedInstall($this->userId); + + throw $exception; + } + } + + public function failed(Throwable $exception): void + { + $label = $this->zipPath ? basename((string) $this->zipPath) : ($this->url ?? 'plugin'); + event(new PluginLog( + 'Plugin installation failed: ' . $this->publicErrorMessage($exception), + 'error', + $label, + $this->userId + )); + } + + /** + * Drop credentials that a process timeout can embed in its command line. + */ + private function publicErrorMessage(Throwable $exception): string + { + return PluginManager::redactHttpUserInfoFromString($exception->getMessage()); + } +} diff --git a/ProcessMaker/Jobs/MoveScriptExecutorToMicroservice.php b/ProcessMaker/Jobs/MoveScriptExecutorToMicroservice.php index 584b7b6f01..1ca70568c9 100644 --- a/ProcessMaker/Jobs/MoveScriptExecutorToMicroservice.php +++ b/ProcessMaker/Jobs/MoveScriptExecutorToMicroservice.php @@ -22,6 +22,6 @@ public function __construct(protected string $uuid) */ public function handle(): void { - \Artisan::call('processmaker:transition-executors --uuid=' . $this->uuid ); + \Artisan::call('processmaker:transition-executors --uuid=' . $this->uuid); } } diff --git a/ProcessMaker/Jobs/ReinstallPlugin.php b/ProcessMaker/Jobs/ReinstallPlugin.php new file mode 100644 index 0000000000..dd192464a9 --- /dev/null +++ b/ProcessMaker/Jobs/ReinstallPlugin.php @@ -0,0 +1,72 @@ +releaseAfter(30) + ->expireAfter(630), + ]; + } + + public function handle(PluginManager $manager): void + { + event(new PluginLog( + 'Starting queued plugin reinstall...', + 'starting', + $this->pluginName, + $this->userId + )); + + $manager->reinstall( + $this->pluginName, + $this->userId, + $this->branch, + $this->tag, + $this->gitUsername, + $this->gitToken, + ); + } + + public function failed(Throwable $exception): void + { + event(new PluginLog( + 'Plugin reinstall failed: ' . $exception->getMessage(), + 'error', + $this->pluginName, + $this->userId + )); + } +} diff --git a/ProcessMaker/Jobs/RunNayraServiceTask.php b/ProcessMaker/Jobs/RunNayraServiceTask.php index 5cd7583234..b1f7d15bb5 100644 --- a/ProcessMaker/Jobs/RunNayraServiceTask.php +++ b/ProcessMaker/Jobs/RunNayraServiceTask.php @@ -25,7 +25,7 @@ class RunNayraServiceTask implements ShouldQueue /** * Create a new job instance. * - * @param \ProcessMaker\Models\ProcessRequestToken $token + * @param ProcessRequestToken $token * @param array $data */ public function __construct(TokenInterface $token) diff --git a/ProcessMaker/Jobs/SmartInboxExistingTasks.php b/ProcessMaker/Jobs/SmartInboxExistingTasks.php index 371596b7f4..6f50d306ed 100644 --- a/ProcessMaker/Jobs/SmartInboxExistingTasks.php +++ b/ProcessMaker/Jobs/SmartInboxExistingTasks.php @@ -2,22 +2,23 @@ namespace ProcessMaker\Jobs; +use Facades\ProcessMaker\InboxRules\ApplyAction; +use Facades\ProcessMaker\InboxRules\MatchingTasks; +use Facades\ProcessMaker\Models\InboxRule; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldBeUnique; use Illuminate\Contracts\Queue\ShouldQueue; +use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; -use Facades\ProcessMaker\InboxRules\MatchingTasks; -use Facades\ProcessMaker\InboxRules\ApplyAction; -use Facades\ProcessMaker\Models\InboxRule; -use Illuminate\Database\Eloquent\ModelNotFoundException; class SmartInboxExistingTasks implements ShouldQueue { use Dispatchable, InteractsWithQueue, Queueable, SerializesModels; public int $inboxRuleId; + /** * Create a new job instance. */ diff --git a/ProcessMaker/Jobs/TestScript.php b/ProcessMaker/Jobs/TestScript.php index 4a5050d2d0..48ce1cbc82 100644 --- a/ProcessMaker/Jobs/TestScript.php +++ b/ProcessMaker/Jobs/TestScript.php @@ -9,8 +9,13 @@ use Illuminate\Queue\SerializesModels; use ProcessMaker\Enums\ScriptExecutorType; use ProcessMaker\Events\ScriptResponseEvent; +use ProcessMaker\Exception\ConfigurationException; +use ProcessMaker\Facades\ScriptRuntime; use ProcessMaker\Models\Script; use ProcessMaker\Models\User; +use ProcessMaker\ScriptRunners\InProcessPhpRunner; +use ProcessMaker\ScriptRuntime\ScriptExecutionContext; +use ProcessMaker\Services\ScriptExecutionModeResolver; use Throwable; class TestScript implements ShouldQueue @@ -32,6 +37,8 @@ class TestScript implements ShouldQueue protected $nonce; + protected bool $runInProcess; + /** * Create a new job instance to execute a script. * @@ -40,15 +47,25 @@ class TestScript implements ShouldQueue * @param string $code * @param array $data * @param array $configuration + * @param string|null $nonce + * @param bool $runInProcess Use Core Service Task in-process runner (no Docker) */ - public function __construct(Script $script, User $current_user, $code, array $data, array $configuration, $nonce = null) - { + public function __construct( + Script $script, + User $current_user, + $code, + array $data, + array $configuration, + $nonce = null, + bool $runInProcess = false + ) { $this->script = $script; $this->current_user = $current_user; $this->code = $code; $this->data = $data; $this->configuration = $configuration; $this->nonce = $nonce; + $this->runInProcess = $runInProcess; } /** @@ -61,6 +78,15 @@ public function handle() try { // Just set the code but do not save the object (preview only) $this->script->code = $this->code; + + if ($this->runInProcess) { + $response = $this->runInProcessPreview(); + \Log::debug('Response from in-process preview: ' . print_r($response, true)); + $this->sendResponse(200, $response); + + return; + } + $metadata = [ 'nonce' => $this->nonce, 'current_user' => $this->current_user?->id, @@ -79,6 +105,76 @@ public function handle() } } + /** + * Preview using ScriptRuntime modules (default) or bare InProcessPhpRunner. + * + * @return array{output: mixed} + */ + private function runInProcessPreview(): array + { + if (!config('core-service-task.enabled')) { + throw new ConfigurationException( + 'Core Service Task is disabled. Set CORE_SERVICE_TASK_ENABLED=true to enable.' + ); + } + + if (strtolower((string) $this->script->language) !== 'php') { + throw new ConfigurationException('In-process preview only supports PHP scripts'); + } + + $user = User::find($this->script->run_as_user_id); + if (!$user) { + throw new ConfigurationException('A user is required to run scripts'); + } + + $timeout = (int) ($this->script->timeout ?: config('core-service-task.default_timeout', 60)); + $max = (int) config('core-service-task.max_timeout', 300); + if ($max > 0 && $timeout > $max) { + $timeout = $max; + } + $timeout = max(1, $timeout); + + $executionMode = app(ScriptExecutionModeResolver::class)->resolve($this->script); + if ( + $executionMode === Script::EXECUTION_MODE_MODULES + && !$this->canUseModules() + ) { + $executionMode = Script::EXECUTION_MODE_BARE; + } + + if ($executionMode === Script::EXECUTION_MODE_MODULES) { + $context = new ScriptExecutionContext( + data: $this->data, + config: $this->configuration, + user: $user, + tokenId: '', + timeout: $timeout, + scriptId: (int) $this->script->id, + source: 'preview', + ); + $output = ScriptRuntime::run($this->code, $context); + } else { + $output = app(InProcessPhpRunner::class)->run( + $this->code, + $this->data, + $this->configuration, + $timeout, + $user + ); + } + + // Match runScript() response shape expected by the Script Editor UI + return ['output' => $output]; + } + + private function canUseModules(): bool + { + return (bool) ( + $this->current_user?->is_administrator + || $this->current_user?->can('run-in-process-modules') + ); + } + /** * Send a response to the user interface * diff --git a/ProcessMaker/Jobs/TogglePlugin.php b/ProcessMaker/Jobs/TogglePlugin.php new file mode 100644 index 0000000000..63998fe9e7 --- /dev/null +++ b/ProcessMaker/Jobs/TogglePlugin.php @@ -0,0 +1,68 @@ +releaseAfter(30) + ->expireAfter(630), + ]; + } + + public function handle(PluginManager $manager): void + { + event(new PluginLog( + "Starting queued plugin toggle: {$this->pluginName}", + 'starting', + $this->pluginName, + $this->userId + )); + + $enabled = $manager->toggle($this->pluginName, $this->userId); + $state = $enabled ? 'enabled' : 'disabled'; + event(new PluginLog( + "Plugin {$this->pluginName} {$state}", + 'done', + $this->pluginName, + $this->userId + )); + } + + public function failed(Throwable $exception): void + { + event(new PluginLog( + 'Plugin toggle failed: ' . $exception->getMessage(), + 'error', + $this->pluginName, + $this->userId + )); + } +} diff --git a/ProcessMaker/Jobs/UninstallPlugin.php b/ProcessMaker/Jobs/UninstallPlugin.php new file mode 100644 index 0000000000..e024471ab3 --- /dev/null +++ b/ProcessMaker/Jobs/UninstallPlugin.php @@ -0,0 +1,61 @@ +releaseAfter(30) + ->expireAfter(630), + ]; + } + + public function handle(PluginManager $manager): void + { + event(new PluginLog( + "Starting queued plugin uninstallation: {$this->pluginName}", + 'starting', + $this->pluginName, + $this->userId + )); + + $manager->uninstall($this->pluginName, $this->userId); + } + + public function failed(Throwable $exception): void + { + event(new PluginLog( + 'Plugin uninstallation failed: ' . $exception->getMessage(), + 'error', + $this->pluginName, + $this->userId + )); + } +} diff --git a/ProcessMaker/JsonColumnIndex.php b/ProcessMaker/JsonColumnIndex.php index bcdae6e57d..a7322dfe10 100644 --- a/ProcessMaker/JsonColumnIndex.php +++ b/ProcessMaker/JsonColumnIndex.php @@ -23,6 +23,7 @@ public function add(string $table, string $column, string $path) if (!config('database.enable_index_json_columns')) { Log::warning('Indexing JSON columns is disabled. The following index was not created: ' . $sql); + return false; } diff --git a/ProcessMaker/Listeners/HandleActivityCompletedRedirect.php b/ProcessMaker/Listeners/HandleActivityCompletedRedirect.php index 95c9cd253f..91ad7e2a57 100644 --- a/ProcessMaker/Listeners/HandleActivityCompletedRedirect.php +++ b/ProcessMaker/Listeners/HandleActivityCompletedRedirect.php @@ -6,7 +6,6 @@ class HandleActivityCompletedRedirect extends HandleRedirectListener { - /** * Handle the event. */ diff --git a/ProcessMaker/Logging/CreateTestLogger.php b/ProcessMaker/Logging/CreateTestLogger.php index b73409d56d..3ddce5a3c7 100644 --- a/ProcessMaker/Logging/CreateTestLogger.php +++ b/ProcessMaker/Logging/CreateTestLogger.php @@ -11,7 +11,7 @@ class CreateTestLogger * Create a custom Monolog instance. * * @param array $config - * @return \Monolog\Logger + * @return Logger */ public function __invoke(array $config) { diff --git a/ProcessMaker/Managers/ModelerManager.php b/ProcessMaker/Managers/ModelerManager.php index e762e3ef23..dbdf783bc2 100644 --- a/ProcessMaker/Managers/ModelerManager.php +++ b/ProcessMaker/Managers/ModelerManager.php @@ -15,6 +15,7 @@ class ModelerManager public function __construct() { $this->javascriptRegistry = []; + $this->javascriptParamsRegistry = []; // Include our default javascript for our core controls $this->addScript(mix('js/processes/modeler/initialLoad.js')); } @@ -32,6 +33,15 @@ public function __construct() */ public function addScript($script, array $params = []) { + // Skip a URL that is already registered; the same script must render only one + + + + diff --git a/resources/js/admin/plugins/components/PluginOutput.vue b/resources/js/admin/plugins/components/PluginOutput.vue new file mode 100644 index 0000000000..42d3f4801d --- /dev/null +++ b/resources/js/admin/plugins/components/PluginOutput.vue @@ -0,0 +1,191 @@ + + + + + \ No newline at end of file diff --git a/resources/js/admin/plugins/index.js b/resources/js/admin/plugins/index.js new file mode 100644 index 0000000000..ad6dec3376 --- /dev/null +++ b/resources/js/admin/plugins/index.js @@ -0,0 +1,6 @@ +import Plugins from "./Plugins"; + +new Vue({ + el: "#plugins", + components: { Plugins }, +}); diff --git a/resources/js/admin/plugins/mcpSetupPrompt.js b/resources/js/admin/plugins/mcpSetupPrompt.js new file mode 100644 index 0000000000..25008e4d61 --- /dev/null +++ b/resources/js/admin/plugins/mcpSetupPrompt.js @@ -0,0 +1,112 @@ +/** + * Builds the "Coding Agent Setup" prompt shown in the Create Plugin dialog. + * + * Pure functions, no Vue or DOM access, so the logic can be checked on its own. + * + * The prompt must never contain secrets: the Git token typed in the dialog is only used by + * ProcessMaker to clone private repositories and is deliberately not an input here, and any + * credentials embedded in the repository URL are stripped before it is used. + */ + +export const MCP_ENDPOINT_PATHS = [ + "/mcp/processes", + "/mcp/screens", + "/mcp/data-connectors", + "/mcp/flow-genies", +]; + +export const MCP_PROFILE_VALUES = ["pm4", "migration"]; + +// Values are typed by the user and end up inside a prompt, so drop all whitespace +// (URLs, branches and usernames never contain any) to keep each value on one line. +const clean = (value) => String(value ?? "").replace(/\s+/g, ""); + +/** + * Drops HTTP userinfo (https://user:secret@host/..., https://token@host/...) from a URL. + * Same two passes as PluginManager::redactHttpUserInfoFromString() in core: a pasted clone URL + * with credentials must never reach the prompt, the clipboard or the agent transcript. + */ +export function stripUrlUserInfo(value) { + return clean(value) + .replace(/:\/\/[^/\s:@]+:[^/\s@]+@/g, "://") + .replace(/:\/\/[^/\s@]+@/g, "://"); +} + +/** + * Same rule as PluginManager::extractRepoName() in core: core installs the plugin as + * storage/plugins/{repoName} and runs `{repoName}:install`, so the plugin folder created + * from package-skeleton must carry exactly this name. + */ +export function extractRepoName(repoUrl) { + const url = clean(repoUrl).replace(/(\.git|\/)$/, ""); + const match = url.match(/\/([^/]+)$/); + return match ? match[1] : ""; +} + +/** True for an https URL that has a path (https://host/org/repo), the only kind core installs. */ +export function isUsableRepoUrl(repoUrl) { + try { + const parsed = new URL(clean(repoUrl)); + return parsed.protocol === "https:" && parsed.pathname.replace(/\/+$/, "") !== ""; + } catch (e) { + return false; + } +} + +/** + * @param {object} options + * @param {string} options.origin ProcessMaker instance URL (window.location.origin) + * @param {string} [options.repoUrl] + * @param {string} [options.branch] + * @param {string} [options.username] + * @param {string} [options.profile] "pm4" or "migration" + * @returns {string} + */ +export function buildMcpSetupPrompt({ + origin, + repoUrl = "", + branch = "", + username = "", + profile = "pm4", +}) { + const base = clean(origin).replace(/\/+$/, ""); + const url = stripUrlUserInfo(repoUrl); + const repoName = isUsableRepoUrl(url) ? extractRepoName(url) : ""; + + const values = [ + ["PM_BASE_URL", base], + ["PLUGIN_REPO", url || ""], + ["PLUGIN_NAME", repoName || ""], + ["PLUGIN_BRANCH", clean(branch) || "main"], + ["GIT_USERNAME", clean(username) || ""], + ["PROFILE", MCP_PROFILE_VALUES.includes(profile) ? profile : "pm4"], + ]; + const width = Math.max(...values.map(([name]) => name.length)); + + return [ + "Set up a ProcessMaker plugin workspace for this instance.", + "", + "Values (PLUGIN_NAME must equal the repository name):", + ...values.map(([name, value]) => ` ${name.padEnd(width)} = ${value}`), + "", + "Before anything else, check `git --version` and `node -v` (Node >= 22; 24 is recommended).", + "If one is missing, show me the install command for my OS and wait for my confirmation before running it.", + "", + "Then install the setup skill and follow it with the values above:", + " npx skills add processmaker/skills -y --skill pm4-plugin-setup", + "", + "The skill checks PHP and Composer, scaffolds the plugin from package-skeleton, builds it,", + "commits it (including the public/ folder) and pushes it to PLUGIN_REPO with my local git credentials.", + "", + "MCP endpoints (authorize them with OAuth in my IDE; no token is needed):", + ...MCP_ENDPOINT_PATHS.map((path) => ` - ${base}${path}`), + "", + "Rules:", + "- Never ask me to paste a git token or an API token in this chat.", + " Tell me to add my ProcessMaker API token to .env as PM_SYNC_TOKEN myself.", + "- Call get-mcp-guidance before other ProcessMaker MCP tools, then load only the matching skills.", + "- Do not invent MCP tool names; discover them from the connected servers.", + "- When you are done, summarize what passed and tell me to open Admin > Plugins, click Plugin,", + " enter PLUGIN_REPO and PLUGIN_BRANCH, and click Save.", + ].join("\n"); +} diff --git a/resources/js/admin/plugins/output.js b/resources/js/admin/plugins/output.js new file mode 100644 index 0000000000..46a5a78e44 --- /dev/null +++ b/resources/js/admin/plugins/output.js @@ -0,0 +1,6 @@ +import PluginOutput from "./components/PluginOutput"; + +new Vue({ + el: "#plugin-output", + components: { PluginOutput }, +}); diff --git a/resources/js/admin/settings/components/McpSkills.vue b/resources/js/admin/settings/components/McpSkills.vue new file mode 100644 index 0000000000..de526d769d --- /dev/null +++ b/resources/js/admin/settings/components/McpSkills.vue @@ -0,0 +1,277 @@ + + + diff --git a/resources/js/admin/settings/index.js b/resources/js/admin/settings/index.js index 3a7cc2fa6b..20ab672c03 100644 --- a/resources/js/admin/settings/index.js +++ b/resources/js/admin/settings/index.js @@ -3,9 +3,11 @@ import * as ScreenBuilder from "@processmaker/screen-builder"; import "@processmaker/screen-builder/dist/vue-form-builder.css"; import SettingsGroups from "./components/SettingsGroups.vue"; import SettingsMain from "./components/SettingsMain.vue"; +import McpSkills from "./components/McpSkills.vue"; window.ScreenBuilder = ScreenBuilder; window.Vue.use(ScreenBuilder.default); +window.__setting_component_McpSkills = McpSkills; new Vue({ el: "#settings", diff --git a/resources/js/components/shared/Modal.vue b/resources/js/components/shared/Modal.vue index 5e3b273977..ce20062f8d 100644 --- a/resources/js/components/shared/Modal.vue +++ b/resources/js/components/shared/Modal.vue @@ -14,6 +14,8 @@ :header-class="headerClass" :footer-class="footerClass" :content-class="contentClass" + :no-close-on-esc="noCloseOnEsc" + :hide-header-close="hideHeaderClose" :size="size" :ok-only="okOnly" no-close-on-backdrop @@ -134,7 +136,9 @@ "titleIcon", "headerClass", "footerClass", - "contentClass" + "contentClass", + "noCloseOnEsc", + "hideHeaderClose" ], data() { return { diff --git a/resources/js/processes/screen-builder/screen.vue b/resources/js/processes/screen-builder/screen.vue index a9912c5f7c..2d13af2a82 100644 --- a/resources/js/processes/screen-builder/screen.vue +++ b/resources/js/processes/screen-builder/screen.vue @@ -122,6 +122,133 @@ id="showDataInput" v-model="showDataInput" > + + +
+ + +
+
= this.previewPresets.length) { + return null; + } + return index; + }, + previewPresetDirty() { + const index = this.normalizedActivePreviewPresetIndex; + if (index === null || !this.previewInputValid) { + return false; + } + return !_.isEqual( + JSON.parse(this.previewInput), + this.getPresetDataObject(this.previewPresets[index]), + ); + }, + previewPresetsForApi() { + return this.previewPresets.map((preset) => ({ + title: preset.title, + // string: PHP json_decode turns {} into [] if data is an object + data: this.serializePresetData(preset.data), + })); + }, displayBuilder() { return this.mode === "editor"; }, @@ -687,6 +875,7 @@ export default { computed: this.computed, custom_css: this.customCSS, watchers: this.watchers, + preview_presets: this.previewPresetsForApi, }) .then(() => { // Set draft status. @@ -759,6 +948,138 @@ export default { this.updateDataPreview(); } }, 1000), + previewPresetRowCss(index) { + return index % 2 === 0 ? "striped" : "bg-default"; + }, + normalizePreviewPresets(presets) { + if (!Array.isArray(presets)) { + return []; + } + return presets.map((preset) => ({ + title: preset.title || "", + data: this.serializePresetData(preset.data), + })); + }, + serializePresetData(data) { + if (typeof data === "string") { + try { + return JSON.stringify(JSON.parse(data)); + } catch (err) { + return "{}"; + } + } + return JSON.stringify(data ?? {}); + }, + getPresetDataObject(preset) { + if (!preset) { + return {}; + } + if (typeof preset.data === "string") { + try { + return JSON.parse(preset.data); + } catch (err) { + return {}; + } + } + return preset.data ?? {}; + }, + persistPreviewPresets() { + this.screen.preview_presets = this.previewPresetsForApi; + this.handleAutosave(true); + }, + applyPreviewPreset(index) { + const presetIndex = Number(index); + const preset = this.previewPresets[presetIndex]; + if (!preset || typeof preset.data === "undefined") { + return; + } + this.activePreviewPresetIndex = presetIndex; + this.previewInput = JSON.stringify(this.getPresetDataObject(preset), null, 2); + this.previewData = JSON.parse(this.previewInput); + this.previewDataStringify = this.previewInput; + this.rendererKey += 1; + if (this.mode === "preview") { + this.$dataProvider.flushScreenCache(); + } + }, + updateActivePreviewPreset() { + const index = this.normalizedActivePreviewPresetIndex; + if (index === null || !this.previewInputValid) { + return; + } + this.$set( + this.previewPresets[index], + "data", + this.serializePresetData(JSON.parse(this.previewInput)), + ); + this.persistPreviewPresets(); + }, + discardPreviewPresetChanges() { + const index = this.normalizedActivePreviewPresetIndex; + if (index === null) { + return; + } + this.applyPreviewPreset(index); + }, + addPreviewPreset() { + if (!this.previewInputValid) { + ProcessMaker.alert(this.$t("Invalid JSON Data Object"), "danger"); + return; + } + this.previewPresetCardType = "insert"; + this.previewPresetTitle = ""; + this.previewPresetEditIndex = null; + this.showPreviewPresetCard = true; + }, + showEditPreviewPreset(index) { + this.previewPresetCardType = "edit"; + this.previewPresetEditIndex = Number(index); + this.previewPresetTitle = this.previewPresets[this.previewPresetEditIndex].title; + this.showPreviewPresetCard = true; + }, + cancelPreviewPresetCard() { + this.showPreviewPresetCard = false; + this.previewPresetEditIndex = null; + this.previewPresetTitle = ""; + }, + savePreviewPresetCard() { + const title = (this.previewPresetTitle || "").trim(); + if (!title) { + return; + } + if (this.previewPresetCardType === "insert") { + if (!this.previewInputValid) { + return; + } + this.previewPresets.push({ + title, + data: this.serializePresetData(JSON.parse(this.previewInput)), + }); + this.activePreviewPresetIndex = this.previewPresets.length - 1; + } else { + const preset = this.previewPresets[this.previewPresetEditIndex]; + if (!preset) { + return; + } + this.$set(preset, "title", title); + } + this.cancelPreviewPresetCard(); + this.persistPreviewPresets(); + }, + removePreviewPreset(index) { + const removeIndex = Number(index); + const active = this.normalizedActivePreviewPresetIndex; + this.previewPresets.splice(removeIndex, 1); + if (active === removeIndex) { + this.activePreviewPresetIndex = null; + } else if (active !== null && active > removeIndex) { + this.activePreviewPresetIndex = active - 1; + } + this.persistPreviewPresets(); + }, + onPreviewPresetsReorder() { + this.persistPreviewPresets(); + }, // eslint-disable-next-line func-names updateDataPreview: debounce(function () { this.previewDataStringify = JSON.stringify(this.previewData, null, 2); @@ -880,6 +1201,9 @@ export default { that.computed = that.screen.computed ? that.screen.computed : []; that.customCSS = that.screen.custom_css ? that.screen.custom_css : ""; that.watchers = that.screen.watchers ? that.screen.watchers : []; + that.previewPresets = that.normalizePreviewPresets( + that.screen.preview_presets, + ); that.previewInput = "{}"; that.preview.custom_css = that.customCSS; ProcessMaker.EventBus.$emit("screen-builder-start", that); @@ -976,7 +1300,7 @@ export default { const data = item.config || {}; const rules = {}; - item.inspector.forEach((property) => { + (item.inspector || []).forEach((property) => { if (property.config.validation) { if ( property.config.validation.includes( @@ -1167,6 +1491,7 @@ export default { computed: this.computed, custom_css: this.customCSS, watchers: this.watchers, + preview_presets: this.previewPresetsForApi, }) .then((response) => { if (exportScreen) { @@ -1289,6 +1614,20 @@ body { max-width: 265px; } +.preview-presets { + max-height: 220px; + overflow-y: auto; + font-size: 0.875rem; + + .striped { + background-color: rgba(0, 0, 0, 0.05); + } + + .fa-plus-square { + cursor: pointer; + } +} + .data-collapse { height: 225px; } diff --git a/resources/js/processes/screen-builder/typeDisplay.js b/resources/js/processes/screen-builder/typeDisplay.js index 6736811069..211e2136ca 100644 --- a/resources/js/processes/screen-builder/typeDisplay.js +++ b/resources/js/processes/screen-builder/typeDisplay.js @@ -15,6 +15,7 @@ ProcessMaker.EventBus.$on("screen-builder-init", (manager) => { const FormAnalyticsChart = FormBuilderControls.find((control) => control.rendererBinding === "FormAnalyticsChart"); const FormCollectionViewControl = FormBuilderControls.find((control) => control.rendererBinding === "FormCollectionViewControl"); const CaseProgressBar = FormBuilderControls.find((control) => control.rendererBinding === "CaseProgressBar"); + const VueRenderControl = FormBuilderControls.find((control) => control.rendererBinding === "VueRenderPreview"); // Remove editable inspector props FormRecordList.control.inspector = FormRecordList.control.inspector.filter((prop) => prop.field !== "editable" && prop.field !== "form"); @@ -34,7 +35,8 @@ ProcessMaker.EventBus.$on("screen-builder-init", (manager) => { FormAnalyticsChart, FormCollectionViewControl, CaseProgressBar, - ]; + VueRenderControl, + ].filter(Boolean); controlsDisplay.forEach((item) => { item.control.inspector.push(...globalProperties[0].inspector); diff --git a/resources/lang/en.json b/resources/lang/en.json index 87674aa096..63e6131518 100644 --- a/resources/lang/en.json +++ b/resources/lang/en.json @@ -193,6 +193,7 @@ "Are you sure you want to delete the auth client": "Are you sure you want to delete the auth client", "Are you sure you want to delete the calc ?:": "Are you sure you want to delete the calc ?", "Are you sure you want to delete the environment variable {{ name }} ?": "Are you sure you want to delete the environment variable {{ name }} ?", + "Are you sure you want to delete the plugin {{ name }}?": "Are you sure you want to delete the plugin {{ name }}?", "Are you sure you want to delete the screen {{item}}? Deleting this asset will break any active tasks that are assigned.": "Are you sure you want to delete the screen {{item}}? Deleting this asset will break any active tasks that are assigned.", "Are you sure you want to delete the token ": "Are you sure you want to delete the token ", "Are you sure you want to delete the user": "Are you sure you want to delete the user", @@ -304,6 +305,8 @@ "BPMN Issues": "BPMN Issues", "BPMN validation issues. Request cannot be started.": "BPMN validation issues. Request cannot be started.", "BPMN": "BPMN", + "Branch": "Branch", + "Branch must be a valid branch name": "Branch must be a valid branch name", "Browse": "Browse", "Browser": "Browser", "Build Command Output": "Build Command Output", @@ -518,6 +521,7 @@ "Create new copies of bundle assets.": "Create new copies of bundle assets.", "Create new DevLink": "Create new DevLink", "Create Notifications": "Create Notifications", + "Create Plugin": "Create Plugin", "Create Process Categories": "Create Process Categories", "Create Process Category": "Create Process Category", "Create Process": "Create Process", @@ -635,6 +639,7 @@ "Delete Groups": "Delete Groups", "Delete Notifications": "Delete Notifications", "Delete Page": "Delete Page", + "Delete Plugin": "Delete Plugin", "Delete Process Categories": "Delete Process Categories", "Delete Record": "Delete Record", "Delete Screen Categories": "Delete Screen Categories", @@ -744,6 +749,7 @@ "Edit Option": "Edit Option", "Edit Page Title": "Edit Page Title", "Edit Page": "Edit Page", + "Edit Plugin": "Edit Plugin", "Edit Process Categories": "Edit Process Categories", "Edit Process Category": "Edit Process Category", "Edit Process": "Edit Process", @@ -1589,6 +1595,17 @@ "Please wait while the files are generated. The screen will be updated when finished.": "Please wait while the files are generated. The screen will be updated when finished.", "Please wait while your content is loaded": "Please wait while your content is loaded", "Please wait": "Please wait", + "Plugin": "Plugin", + "Plugins": "Plugins", + "Plugin Installation Output": "Plugin Installation Output", + "Plugin Uninstallation Output": "Plugin Uninstallation Output", + "Plugin Toggle Output": "Plugin Toggle Output", + "Uninstall Plugin": "Uninstall Plugin", + "Plugin successfully uninstalled. You can now close this window.": "Plugin successfully uninstalled. You can now close this window.", + "Plugin successfully updated. You can now close this window.": "Plugin successfully updated. You can now close this window.", + "Error uninstalling plugin. See output above.": "Error uninstalling plugin. See output above.", + "Error toggling plugin. See output above.": "Error toggling plugin. See output above.", + "Plugin Successfully Installed. You can now close this window. ": "Plugin Successfully Installed. You can now close this window. ", "PM Block Name": "PM Block Name", "PM Blocks": "PM Blocks", "Pm_block_category": "PM Block Category", @@ -1717,6 +1734,8 @@ "Repeat on": "Repeat on", "Report an issue": "Report an issue", "Repository Name": "Repository Name", + "Repository URL": "Repository URL", + "Repository URL must be a valid URL": "Repository URL must be a valid URL", "Request All": "Request All", "Request Canceled": "Request Canceled", "Request Commented": "Request Commented", @@ -2140,6 +2159,7 @@ "Table Prompt Suffix": "Table Prompt Suffix", "Table": "Table", "Tag": "Tag", + "Tag must be a valid tag name": "Tag must be a valid tag name", "Takes precedence over value set in data.": "Takes precedence over value set in data.", "Task :task_id could not be reassigned because the task settings prevent it from being reassigned": "Task :task_id could not be reassigned because the task settings prevent it from being reassigned", "Task {{- subject }} completed by {{- user }}": "Task {{- subject }} completed by {{- user }}", @@ -2280,6 +2300,8 @@ "The package is not installed": "The package is not installed", "The page you are looking for could not be found": "The page you are looking for could not be found", "The placeholder is what is shown in the field when no value is provided yet": "The placeholder is what is shown in the field when no value is provided yet", + "The plugin was toggled.": "The plugin was toggled.", + "The plugin was deleted.": "The plugin was deleted.", "The PM Block name must be unique.": "The PM Block name must be unique.", "The Process field is required.": "The Process field is required.", "The process name must be unique.": "The process name must be unique.", @@ -2413,6 +2435,7 @@ "Toggle Configuration": "Toggle Configuration", "Toggle Notifications": "Toggle Notifications", "Toggle Show Password": "Toggle Show Password", + "Toggle": "Toggle", "Toggle Style": "Toggle Style", "Token URL": "Token URL", "Token_id": "Token ID", @@ -2420,6 +2443,7 @@ "TokenCreated": "Token Created", "TokenDeleted": "Token Deleted", "Tokens": "Tokens", + "Toggle Plugin": "Toggle Plugin", "Too many login attempts. Please try again in :seconds seconds.": "Too many login attempts. Please try again in :seconds seconds.", "Tooltip Contains": "Tooltip Contains", "Tooltip": "Tooltip", diff --git a/resources/lang/es.json b/resources/lang/es.json index cb2e96816f..6e51100555 100644 --- a/resources/lang/es.json +++ b/resources/lang/es.json @@ -289,6 +289,8 @@ "BPMN Issues": "Problemas de BPMN", "BPMN validation issues. Request cannot be started.": "Problemas de validación de BPMN. No se puede iniciar la solicitud.", "BPMN": "BPMN", + "Branch": "Rama", + "Branch must be a valid branch name": "La rama debe ser una rama válida", "Browse": "Examinar", "Browser": "Navegador", "Build Command Output": "Generar salida de comando", @@ -494,6 +496,7 @@ "Create new copies of bundle assets.": "Crear nuevas copias de los activos del paquete.", "Create new DevLink": "Crear nuevo DevLink", "Create Notifications": "Crear notificaciones", + "Create Plugin": "Crear plugin", "Create Process Categories": "Crear categorías de procesos", "Create Process Category": "Crear categoría de procesos", "Create Process": "Crear proceso", @@ -610,6 +613,7 @@ "Delete Groups": "Eliminar grupos", "Delete Notifications": "Eliminar notificaciones", "Delete Page": "Eliminar página", + "Delete Plugin": "Eliminar plugin", "Delete Process Categories": "Borrar las categorías de proceso", "Delete Record": "Eliminar registro", "Delete Screen Categories": "Eliminar categorías de pantalla", @@ -715,6 +719,7 @@ "Edit Option": "Editar opción", "Edit Page Title": "Editar título de página", "Edit Page": "Editar página", + "Edit Plugin": "Editar plugin", "Edit Process Categories": "Editar categorías de procesos", "Edit Process Category": "Editar categoría de procesos", "Edit Process": "Editar proceso", @@ -1527,6 +1532,10 @@ "Please wait while the files are generated. The screen will be updated when finished.": "Espere mientras se generan los archivos. La pantalla se actualizará cuando termine.", "Please wait while your content is loaded": "Espere mientras se carga su contenido", "Please wait": "Por favor espera", + "Plugin": "Plugin", + "Plugins": "Plugins", + "Plugin Installation Output": "Resultado de la instalación de plugin", + "Plugin Successfully Installed. You can now close this window. ": "Plugin instalado correctamente. Puede cerrar esta ventana.", "PM Block Name": "Nombre del Bloque PM", "PM Blocks": "Bloques PM", "Pm_block_category": "Categoría de Bloque PM", @@ -1652,6 +1661,8 @@ "Repeat on": "Repetir en", "Report an issue": "Reportar un problema", "Repository Name": "Nombre del Repositorio", + "Repository URL": "URL del Repositorio", + "Repository URL must be a valid URL": "La URL del repositorio debe ser una URL válida", "Request All": "Todas las solicitudes", "Request Canceled": "Solicitud cancelada", "Request Commented": "Solicitud Comentada", @@ -2068,6 +2079,7 @@ "Table": "Tabla", "Table Prompt Suffix": "Sufijo del Mensaje de Tabla", "Tag": "Etiqueta", + "Tag must be a valid tag name": "La etiqueta debe ser una etiqueta válida", "take care of things automatically.": "se encargan de las cosas automáticamente.", "Takes precedence over value set in data.": "Tiene prioridad sobre el conjunto de valores en los datos.", "Task :task_id could not be reassigned because the task settings prevent it from being reassigned": "La tarea :task_id no pudo ser reasignada porque la configuración de la tarea lo impide", @@ -2204,6 +2216,8 @@ "The package is not installed": "El paquete no esta instalado", "The page you are looking for could not be found": "No se pudo encontrar la página que está buscando", "The placeholder is what is shown in the field when no value is provided yet": "El marcador de posición es lo que se muestra en el campo cuando aún no se proporciona ningún valor", + "The plugin was toggled.": "El plugin fue activado/desactivado.", + "The plugin was deleted.": "El plugin fue eliminado.", "The PM Block name must be unique.": "El nombre del bloque PM debe ser único.", "The Process field is required.": "El campo Proceso es obligatorio.", "The process name must be unique.": "El nombre del proceso debe ser único.", @@ -2342,6 +2356,8 @@ "TokenCreated": "Token Creado", "TokenDeleted": "Token Eliminado", "Tokens": "Tokens", + "Toggle": "Alternar", + "Toggle Plugin": "Activar/desactivar plugin", "Too many login attempts. Please try again in :seconds seconds.": "Se han realizado demasiados intentos de inicio de sesión. Inténtelo de nuevo en: segundos segundos.", "Tooltip Contains": "La descripción emergente contiene", "Tooltip": "Descripción emergente", diff --git a/resources/views/admin/plugins/index.blade.php b/resources/views/admin/plugins/index.blade.php new file mode 100644 index 0000000000..775beff3c0 --- /dev/null +++ b/resources/views/admin/plugins/index.blade.php @@ -0,0 +1,31 @@ +@extends('layouts.layoutnextvite') + +@section('title') + {{__('Plugins')}} +@endsection + +@section('sidebar') + @include('layouts.sidebar', ['sidebar'=> Menu::get('sidebar_admin')]) +@endsection + +@section('breadcrumbs') + @include('shared.breadcrumbs', ['routes' => [ + __('Admin') => route('admin.index'), + __('Plugins') => null, + ]]) +@endsection +@section('content') +
+ +
+@endsection + +@section('js') + @vite('resources/js/loader/loaderMinimal.js') + + @vite(['resources/js/admin/plugins/index.js']) +@endsection \ No newline at end of file diff --git a/resources/views/processes/scripts/edit.blade.php b/resources/views/processes/scripts/edit.blade.php index 1ef36139d1..0b25291bee 100644 --- a/resources/views/processes/scripts/edit.blade.php +++ b/resources/views/processes/scripts/edit.blade.php @@ -81,6 +81,38 @@ {{ html()->textarea('description')->id('description')->rows(4)->class('form-control')->attribute('v-model', 'formData.description')->attribute('v-bind:class', '{"form-control":true, "is-invalid":errors.description}')->required()->attribute('aria-required', 'true') }}
+
+
+ + +
+ + {{ __('Run this trusted PHP script in the ProcessMaker worker (no Docker). Requires CORE_SERVICE_TASK_ENABLED. Use Script Runtime modules for package helpers.') }} + + +
+ {{ html()->label(__('Execution mode'), 'execution_mode') }} + {{ html()->select('execution_mode', [ + 'bare' => __('Bare subprocess'), + 'modules' => __('Laravel modules'), + ])->class('form-control')->attribute('v-model', 'formData.execution_mode')->attribute('v-bind:class', '{"form-control":true, "is-invalid":errors.execution_mode}') }} + + {{ __('Laravel modules run inside the worker and should only be used for trusted scripts.') }} + + +
+
user()?->is_administrator || auth()->user()?->can('run-in-process-modules')) + ), editScriptHooks: [], } }, + computed: { + isPhpScript() { + const executor = this.scriptExecutors[this.formData.script_executor_id]; + return executor && String(executor.language).toLowerCase() === 'php'; + }, + }, watch: { selectedProjects: { handler() { this.formData.projects = this.selectedProjects; } - } + }, + isPhpScript(isPhp) { + if (!isPhp) { + this.formData.allow_in_process = false; + this.formData.execution_mode = 'bare'; + } + }, }, methods: { resetErrors() { @@ -186,6 +236,8 @@ title: null, language: null, description: null, + allow_in_process: null, + execution_mode: null, status: null }); }, @@ -207,6 +259,8 @@ retry_attempts: this.formData.retry_attempts, retry_wait_time: this.formData.retry_wait_time, script_executor_id: this.formData.script_executor_id, + allow_in_process: this.isPhpScript ? !!this.formData.allow_in_process : false, + execution_mode: this.isPhpScript ? (this.formData.execution_mode || 'bare') : 'bare', }) .then(() => { ProcessMaker.alert(this.$t('The script was saved.'), 'success'); @@ -226,6 +280,8 @@ }, mounted() { this.selectedProjects = this.assignedProjects.length > 0 ? this.assignedProjects.map(project => project.id) : null; + this.formData.allow_in_process = !!this.formData.allow_in_process; + this.formData.execution_mode = this.formData.execution_mode || 'bare'; } }); }); diff --git a/routes/ai.php b/routes/ai.php new file mode 100644 index 0000000000..46c15f1408 --- /dev/null +++ b/routes/ai.php @@ -0,0 +1,46 @@ +middleware(['auth:api']); + +Mcp::local('screens', ScreenServer::class); + +Mcp::web('/mcp/processes', ProcessServer::class) + ->middleware(['auth:api']); + +Mcp::local('processes', ProcessServer::class); + +Mcp::web('/mcp/data-connectors', DataConnectorsServer::class) + ->middleware(['auth:api']); + +Mcp::local('data-connectors', DataConnectorsServer::class); + +Mcp::web('/mcp/flow-genies', FlowGenieServer::class) + ->middleware(['auth:api']); + +Mcp::local('flow-genies', FlowGenieServer::class); + +Mcp::oauthRoutes(); + +foreach (['screens', 'processes', 'data-connectors', 'flow-genies'] as $server) { + Route::get('/mcp/' . $server, McpProbeController::class); +} diff --git a/routes/api.php b/routes/api.php index f544b47090..14648d0ccf 100644 --- a/routes/api.php +++ b/routes/api.php @@ -10,6 +10,9 @@ use ProcessMaker\Http\Controllers\Api\CommentController; use ProcessMaker\Http\Controllers\Api\CssOverrideController; use ProcessMaker\Http\Controllers\Api\DebugController; +use ProcessMaker\Http\Controllers\Api\DeployProcess; +use ProcessMaker\Http\Controllers\Api\DeployScreen; +use ProcessMaker\Http\Controllers\Api\DeployScript; use ProcessMaker\Http\Controllers\Api\DevLinkController; use ProcessMaker\Http\Controllers\Api\EncryptedDataController; use ProcessMaker\Http\Controllers\Api\EnvironmentVariablesController; @@ -22,6 +25,7 @@ use ProcessMaker\Http\Controllers\Api\NotificationController; use ProcessMaker\Http\Controllers\Api\OpenAIController; use ProcessMaker\Http\Controllers\Api\PermissionController; +use ProcessMaker\Http\Controllers\Api\PluginController; use ProcessMaker\Http\Controllers\Api\ProcessCategoryController; use ProcessMaker\Http\Controllers\Api\ProcessController; use ProcessMaker\Http\Controllers\Api\ProcessLaunchpadController; @@ -47,6 +51,13 @@ use ProcessMaker\Http\Controllers\TestStatusController; Route::middleware('auth:api', 'setlocale', 'bindings', 'sanitize', 'manager')->prefix('api/1.0')->name('api.')->group(function () { + // Plugins + Route::get('plugins', [PluginController::class, 'index'])->name('plugins.index')->middleware('can:manage-plugins'); + Route::post('plugins/install', [PluginController::class, 'install'])->name('plugins.install')->middleware('can:manage-plugins'); + Route::post('plugins/{name}/reinstall', [PluginController::class, 'reinstall'])->name('plugins.reinstall')->middleware('can:manage-plugins'); + Route::delete('plugins/{name}', [PluginController::class, 'destroy'])->name('plugins.destroy')->middleware('can:manage-plugins'); + Route::patch('plugins/{name}/toggle', [PluginController::class, 'toggle'])->name('plugins.toggle')->middleware('can:manage-plugins'); + // Users Route::get('users', [UserController::class, 'index'])->name('users.index'); // Permissions handled in the controller Route::get('users/{user}', [UserController::class, 'show'])->name('users.show'); // Permissions handled in the controller @@ -133,6 +144,26 @@ Route::get('scripts/execution/{key}', [ScriptController::class, 'execution'])->name('scripts.execution'); Route::post('scripts/microservice/execution', [ScriptController::class, 'microserviceExecution']); + // Deploy / sync helpers (core). Canonical paths + package-skeleton aliases for BC. + Route::post('deploy-script', [DeployScript::class, 'deployScript'])->name('deploy-script'); + Route::get('script-php', [DeployScript::class, 'getScriptPhp'])->name('script-php'); + Route::post('deploy-screen', [DeployScreen::class, 'deployScreen'])->name('deploy-screen'); + Route::get('screen-yaml', [DeployScreen::class, 'getScreenYaml'])->name('screen-yaml'); + Route::post('deploy-process', [DeployProcess::class, 'deployProcess'])->name('deploy-process'); + Route::get('process-bpmn', [DeployProcess::class, 'getProcessBpmn'])->name('process-bpmn'); + Route::post('package-skeleton/deploy-script', [DeployScript::class, 'deployScript']) + ->name('package-skeleton.deploy-script'); + Route::get('package-skeleton/script-php', [DeployScript::class, 'getScriptPhp']) + ->name('package-skeleton.script-php'); + Route::post('package-skeleton/deploy-screen', [DeployScreen::class, 'deployScreen']) + ->name('package-skeleton.deploy-screen'); + Route::get('package-skeleton/screen-yaml', [DeployScreen::class, 'getScreenYaml']) + ->name('package-skeleton.screen-yaml'); + Route::post('package-skeleton/deploy-process', [DeployProcess::class, 'deployProcess']) + ->name('package-skeleton.deploy-process'); + Route::get('package-skeleton/process-bpmn', [DeployProcess::class, 'getProcessBpmn']) + ->name('package-skeleton.process-bpmn'); + // Script Categories Route::get('script_categories', [ScriptCategoryController::class, 'index'])->name('script_categories.index')->middleware('can:view-script-categories'); Route::get('script_categories/{script_category}', [ScriptCategoryController::class, 'show'])->name('script_categories.show')->middleware('can:view-script-categories'); diff --git a/routes/web.php b/routes/web.php index c2273f4208..e0c786dac3 100644 --- a/routes/web.php +++ b/routes/web.php @@ -11,6 +11,7 @@ use ProcessMaker\Http\Controllers\Admin\GroupController; use ProcessMaker\Http\Controllers\Admin\LdapLogsController; use ProcessMaker\Http\Controllers\Admin\LogsController; +use ProcessMaker\Http\Controllers\Admin\PluginController; use ProcessMaker\Http\Controllers\Admin\QueuesController; use ProcessMaker\Http\Controllers\Admin\ScriptExecutorController; use ProcessMaker\Http\Controllers\Admin\SettingsController; @@ -78,6 +79,8 @@ Route::get('script-executors', [ScriptExecutorController::class, 'index'])->name('script-executors.index'); + Route::get('plugins', [PluginController::class, 'index'])->name('plugins.index')->middleware('can:manage-plugins'); + // Tenant Jobs Dashboard Route::get('tenant-queues', [TenantQueueController::class, 'index'])->name('tenant-queue.index'); diff --git a/tests/DuskTestCase.php b/tests/DuskTestCase.php index 2af55ba64f..4ab5816933 100644 --- a/tests/DuskTestCase.php +++ b/tests/DuskTestCase.php @@ -25,7 +25,7 @@ public static function prepare() /** * Create the RemoteWebDriver instance. * - * @return \Facebook\WebDriver\Remote\RemoteWebDriver + * @return RemoteWebDriver */ protected function driver() { diff --git a/tests/Feature/Api/ConvertBPMNTest.php b/tests/Feature/Api/ConvertBPMNTest.php index 4dd36be1ea..2c23a64c3e 100644 --- a/tests/Feature/Api/ConvertBPMNTest.php +++ b/tests/Feature/Api/ConvertBPMNTest.php @@ -24,7 +24,7 @@ class ConvertBPMNTest extends TestCase public $withPermissions = true; /** - * Test convert subProcess to callActivity + * Embedded subProcess BPMN is persisted as-is on save (no callActivity conversion). */ public function testConvertSubProcess() { @@ -32,8 +32,14 @@ public function testConvertSubProcess() 'status' => 'ACTIVE', 'bpmn' => file_get_contents(__DIR__ . '/processes/CP.01.00 Create new customer.bpmn'), ]); - $this->assertStringNotContainsString('subProcess', $process->bpmn); - $this->assertEquals(2, Process::count()); + $this->assertEquals(1, Process::count()); + + $document = new BpmnDocument(); + $document->loadXML($process->bpmn); + $subProcesses = $document->getElementsByTagNameNS(BpmnDocument::BPMN_MODEL, 'subProcess'); + $this->assertGreaterThan(0, $subProcesses->length); + $callActivities = $document->getElementsByTagNameNS(BpmnDocument::BPMN_MODEL, 'callActivity'); + $this->assertSame(0, $callActivities->length); } /** diff --git a/tests/Feature/Api/DeployProcessControllerTest.php b/tests/Feature/Api/DeployProcessControllerTest.php new file mode 100644 index 0000000000..e5074a0dcb --- /dev/null +++ b/tests/Feature/Api/DeployProcessControllerTest.php @@ -0,0 +1,246 @@ +create(['title' => 'sample-screen-ref']); + $script = Script::factory()->create(['title' => 'sample-script-ref']); + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => 'sample-process', + 'bpmn' => $this->sampleBpmn( + '${screen:sample-screen-ref}', + '${script:sample-script-ref}' + ), + ]) + ->assertOk() + ->assertJson([ + 'success' => true, + 'action' => 'created', + 'name' => 'sample-process', + ]); + + $process = Process::where('name', 'sample-process')->firstOrFail(); + $this->assertStringContainsString('pm:screenRef="' . $screen->id . '"', $process->bpmn); + $this->assertStringContainsString('pm:scriptRef="' . $script->id . '"', $process->bpmn); + } + + public function testDeployProcessAcceptsDescription(): void + { + $summary = 'Brief summary for the process catalog.'; + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => 'described-process', + 'description' => $summary, + 'bpmn' => $this->sampleBpmn('', ''), + ])->assertOk(); + + $process = Process::where('name', 'described-process')->firstOrFail(); + $this->assertSame($summary, $process->description); + + $updated = $summary . ' Updated.'; + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => 'described-process', + 'description' => $updated, + 'bpmn' => $this->sampleBpmn('', ''), + 'version_name' => 'Update process description', + ])->assertOk(); + + $this->assertSame($updated, $process->refresh()->description); + } + + public function testDeployProcessUpdateRequiresVersionName(): void + { + $name = 'version-name-process'; + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => $name, + 'bpmn' => $this->sampleBpmn('', ''), + ])->assertOk(); + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => $name, + 'bpmn' => $this->sampleBpmn('', ''), + ]) + ->assertStatus(422) + ->assertJsonValidationErrors(['version_name']); + } + + public function testDeployProcessUpdateStoresVersionName(): void + { + if (!class_exists(VersionHistory::class)) { + $this->markTestSkipped('package-versions is not installed.'); + } + + $name = 'version-name-process-stored'; + $summary = 'Adjust BPMN layout'; + + Screen::factory()->create(['title' => 'vn-screen']); + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => $name, + 'bpmn' => $this->sampleBpmn('', ''), + ])->assertOk(); + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => $name, + 'bpmn' => $this->sampleBpmn('${screen:vn-screen}', ''), + 'version_name' => $summary, + ])->assertOk(); + + $process = Process::where('name', $name)->firstOrFail(); + $version = $process->versions()->orderByDesc('id')->first(); + $this->assertInstanceOf(ProcessVersion::class, $version); + + $history = VersionHistory::query() + ->where('versionable_id', $version->id) + ->where('versionable_type', ProcessVersion::class) + ->orderByDesc('id') + ->first(); + + $this->assertNotNull($history); + $this->assertSame($summary, $history->subject); + } + + public function testGetProcessBpmnRestoresNamedReferences(): void + { + Screen::factory()->create(['title' => 'restore-screen']); + Script::factory()->create(['title' => 'restore-script']); + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => 'restore-process', + 'bpmn' => $this->sampleBpmn( + '${screen:restore-screen}', + '${script:restore-script}' + ), + ])->assertOk(); + + $response = $this->apiCall('GET', self::GET_ENDPOINT . '?name=restore-process'); + + $response->assertOk()->assertJsonPath('success', true); + $this->assertStringContainsString('${screen:restore-screen}', $response->json('bpmn')); + $this->assertStringContainsString('${script:restore-script}', $response->json('bpmn')); + } + + public function testDeployAlternativeBWritesDraftAndKeepsLiveProcess(): void + { + $this->requireAbTesting(); + $name = 'alt-b-draft-process'; + $screen = Screen::factory()->create(['title' => 'alt-b-screen']); + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => $name, + 'bpmn' => $this->sampleBpmn('', ''), + ])->assertOk(); + $process = Process::where('name', $name)->firstOrFail(); + $liveBpmn = $process->bpmn; + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => $name, + 'alternative' => 'B', + 'bpmn' => $this->sampleBpmn('${screen:alt-b-screen}', ''), + ]) + ->assertOk() + ->assertJson(['success' => true, 'action' => 'draft', 'alternative' => 'B']); + + $this->assertSame($liveBpmn, $process->refresh()->bpmn, 'Alternative A must not change.'); + $draft = $process->versions()->where('draft', true)->where('alternative', 'B')->firstOrFail(); + $this->assertStringContainsString('pm:screenRef="' . $screen->id . '"', $draft->bpmn); + } + + public function testDeployAlternativeBPublishLinksVersionToAbRecord(): void + { + $this->requireAbTesting(); + $name = 'alt-b-publish-process'; + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => $name, + 'bpmn' => $this->sampleBpmn('', ''), + ])->assertOk(); + $process = Process::where('name', $name)->firstOrFail(); + $liveBpmn = $process->bpmn; + + $response = $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => $name, + 'alternative' => 'B', + 'publish' => true, + 'bpmn' => str_replace('Task_1', 'Task_B', $this->sampleBpmn('', '')), + ])->assertOk()->assertJson(['action' => 'published', 'alternative' => 'B']); + + $this->assertSame($liveBpmn, $process->refresh()->bpmn, 'Alternative A must not change.'); + $version = ProcessVersion::findOrFail($response->json('process_version_id')); + $this->assertSame('B', $version->alternative); + $this->assertFalse((bool) $version->draft); + $this->assertStringContainsString('Task_B', $version->bpmn); + + $alternativeModel = 'ProcessMaker\Package\PackageABTesting\Models\Alternative'; + $record = $alternativeModel::where('process_id', $process->id)->firstOrFail(); + $this->assertSame($version->id, (int) $record->process_version_b_id); + } + + public function testDeployAlternativeBRequiresExistingProcess(): void + { + $this->requireAbTesting(); + + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => 'alt-b-missing-process', + 'alternative' => 'B', + 'bpmn' => $this->sampleBpmn('', ''), + ]) + ->assertStatus(422) + ->assertJsonPath('success', false); + + $this->assertNull(Process::where('name', 'alt-b-missing-process')->first()); + } + + public function testDeployRejectsUnknownAlternative(): void + { + $this->apiCall('POST', self::DEPLOY_ENDPOINT, [ + 'name' => 'alt-unknown-process', + 'alternative' => 'C', + 'bpmn' => $this->sampleBpmn('', ''), + ]) + ->assertStatus(422) + ->assertJsonValidationErrors(['alternative']); + } + + private function requireAbTesting(): void + { + if (!class_exists('ProcessMaker\Package\PackageABTesting\Models\Alternative')) { + $this->markTestSkipped('package-ab-testing is not installed.'); + } + } + + private function sampleBpmn(string $screenReference, string $scriptReference): string + { + return << + + + + + + +XML; + } +} diff --git a/tests/Feature/Api/DeployScreenControllerTest.php b/tests/Feature/Api/DeployScreenControllerTest.php new file mode 100644 index 0000000000..be46a64caf --- /dev/null +++ b/tests/Feature/Api/DeployScreenControllerTest.php @@ -0,0 +1,236 @@ +postJson('/api/1.0' . self::API_ENDPOINT, [ + 'yml_content' => "config: []\n", + 'name' => 'sample-screen', + ])->assertStatus(401); + } + + public function testDeployScreenCreatesFromYaml(): void + { + $yaml = <<<'YAML' +config: + - component: FormBlank + items: [] +computed: [] +watchers: [] +custom_css: '' +YAML; + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => $yaml, + 'name' => 'sample-screen', + ]) + ->assertOk() + ->assertJson([ + 'success' => true, + 'action' => 'created', + 'name' => 'sample-screen', + ]); + + $this->assertNotNull(Screen::where('title', 'sample-screen')->first()); + } + + public function testDeployScreenUpdateRequiresVersionName(): void + { + $name = 'version-name-required-screen'; + $yaml = "config: []\n"; + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => $yaml, + 'name' => $name, + ])->assertOk(); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => "config: []\ncomputed: []\n", + 'name' => $name, + ]) + ->assertStatus(422) + ->assertJsonValidationErrors(['version_name']); + } + + public function testDeployScreenUpdateStoresVersionName(): void + { + if (!class_exists(VersionHistory::class)) { + $this->markTestSkipped('package-versions is not installed.'); + } + + $name = 'version-name-stored-screen'; + $summary = 'Add computed properties'; + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => "config: []\n", + 'name' => $name, + ])->assertOk(); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => "config: []\ncomputed: []\n", + 'name' => $name, + 'version_name' => $summary, + ])->assertOk(); + + $screen = Screen::where('title', $name)->firstOrFail(); + $version = $screen->versions()->orderByDesc('id')->first(); + $this->assertInstanceOf(ScreenVersion::class, $version); + + $history = VersionHistory::query() + ->where('versionable_id', $version->id) + ->where('versionable_type', ScreenVersion::class) + ->orderByDesc('id') + ->first(); + + $this->assertNotNull($history); + $this->assertSame($summary, $history->subject); + } + + public function testGetScreenYamlReturnsYamlForPublishedScreen(): void + { + $yaml = "config: []\n"; + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => $yaml, + 'name' => 'yaml-pull-screen', + ])->assertOk(); + + $response = $this->actingAs($this->user, 'api') + ->get('/api/1.0' . self::GET_ENDPOINT . '?name=yaml-pull-screen'); + + $response->assertOk(); + $this->assertStringContainsString('yaml', (string) $response->headers->get('Content-Type')); + } + + public function testGetScreenYamlAddsEmptyInspectorToEveryItem(): void + { + $yaml = <<<'YAML' +config: + - name: Page 1 + items: + - component: FormInput + inspector: [] + config: + name: first + - component: FormMultiColumn + inspector: [] + container: true + items: + - - component: FormInput + inspector: [] + config: + name: nested + - [] +YAML; + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => $yaml, + 'name' => 'inspector-pull-screen', + ])->assertOk(); + + $pull = $this->actingAs($this->user, 'api') + ->get('/api/1.0' . self::GET_ENDPOINT . '?name=inspector-pull-screen'); + + $pull->assertOk(); + $parsed = \Symfony\Component\Yaml\Yaml::parse($pull->getContent()); + $items = $parsed['config'][0]['items']; + $this->assertSame([], $items[0]['inspector']); + $this->assertSame([], $items[1]['inspector']); + $this->assertSame([], $items[1]['items'][0][0]['inspector']); + $this->assertSame([], $items[1]['items'][1]); + } + + public function testDeployScreenPersistsPreviewPresets(): void + { + $yaml = <<<'YAML' +config: [] +computed: [] +watchers: [] +custom_css: '' +preview_presets: + - title: Empty / start + data: '{}' + - title: Happy path + data: + callsign: AVA123 +YAML; + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => $yaml, + 'name' => 'preset-screen', + ])->assertOk(); + + $screen = Screen::where('title', 'preset-screen')->first(); + $expected = [ + ['title' => 'Empty / start', 'data' => '{}'], + ['title' => 'Happy path', 'data' => '{"callsign":"AVA123"}'], + ]; + $this->assertSame($expected, $screen->preview_presets); + $this->assertSame($expected, $screen->versions()->published()->first()->preview_presets); + + $updated = <<<'YAML' +config: [] +preview_presets: + - title: Updated + data: '{"callsign":"N45XB"}' +YAML; + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => $updated, + 'name' => 'preset-screen', + 'version_name' => 'Update preview presets', + ])->assertOk()->assertJson(['action' => 'updated']); + + $screen->refresh(); + $this->assertSame( + [['title' => 'Updated', 'data' => '{"callsign":"N45XB"}']], + $screen->preview_presets + ); + + $pull = $this->actingAs($this->user, 'api') + ->get('/api/1.0' . self::GET_ENDPOINT . '?name=preset-screen'); + $pull->assertOk(); + $this->assertStringContainsString('Updated', $pull->getContent()); + $this->assertStringContainsString('N45XB', $pull->getContent()); + } + + public function testDeployScreenEncodesEmptyYamlMappingsAsObjects(): void + { + $yaml = <<<'YAML' +config: [] +preview_presets: + - title: Empty mapping + data: {} + - title: Nested empty mapping + data: + callsign: AVA123 + meta: {} +YAML; + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'yml_content' => $yaml, + 'name' => 'preset-empty-maps', + ])->assertOk(); + + $screen = Screen::where('title', 'preset-empty-maps')->first(); + $this->assertSame( + [ + ['title' => 'Empty mapping', 'data' => '{}'], + ['title' => 'Nested empty mapping', 'data' => '{"callsign":"AVA123","meta":{}}'], + ], + $screen->preview_presets + ); + } +} diff --git a/tests/Feature/Api/DeployScriptControllerTest.php b/tests/Feature/Api/DeployScriptControllerTest.php new file mode 100644 index 0000000000..285e706cb9 --- /dev/null +++ b/tests/Feature/Api/DeployScriptControllerTest.php @@ -0,0 +1,437 @@ +postJson('/api/1.0' . self::API_ENDPOINT, [ + 'code' => ' 'sample-sync-script', + ])->assertStatus(401); + } + + public function testDeployScriptValidatesCodeRequired(): void + { + $this->apiCall('POST', self::API_ENDPOINT, [ + 'name' => 'sample-sync-script', + ]) + ->assertStatus(422) + ->assertJson(['success' => false]) + ->assertJsonValidationErrors(['code']); + } + + public function testDeployScriptCreatesWhenTitleDoesNotExist(): void + { + $this->ensureExecutor(); + $code = " true];\n"; + $name = 'sample-sync-script'; + + $response = $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => $code, + 'name' => $name, + ]); + + $response->assertStatus(200) + ->assertJson([ + 'success' => true, + 'action' => 'created', + 'name' => $name, + ]); + + $script = Script::where('title', $name)->first(); + $this->assertNotNull($script); + $this->assertSame(rtrim($code), rtrim((string) $script->code)); + $this->assertSame($this->user->id, $script->run_as_user_id); + } + + public function testCanonicalDeployScriptRouteCreatesScript(): void + { + $this->ensureExecutor(); + + $this->apiCall('POST', self::CANONICAL_ENDPOINT, [ + 'code' => ' true];', + 'name' => 'canonical-sync-script', + ]) + ->assertStatus(200) + ->assertJson([ + 'success' => true, + 'action' => 'created', + 'name' => 'canonical-sync-script', + ]); + } + + public function testDeployScriptUpdatesExistingScriptByTitle(): void + { + $existing = Script::factory()->create([ + 'title' => 'sample-update-script', + 'code' => ' true];', + 'run_as_user_id' => $this->user->id, + ]); + + $newCode = " true];\n"; + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => $newCode, + 'name' => 'sample-update-script', + 'version_name' => 'Refresh script payload', + ]) + ->assertStatus(200) + ->assertJson([ + 'success' => true, + 'action' => 'updated', + 'script_id' => $existing->id, + ]); + + $existing->refresh(); + $this->assertSame(rtrim($newCode), rtrim((string) $existing->code)); + } + + public function testDeployScriptUpdateRequiresVersionName(): void + { + $this->ensureExecutor(); + $name = 'version-name-script'; + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 1];', + 'name' => $name, + ])->assertOk(); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 2];', + 'name' => $name, + ]) + ->assertStatus(422) + ->assertJsonValidationErrors(['version_name']); + } + + public function testDeployScriptUpdateStoresVersionNameWhenCodeUnchangedAndDraftExists(): void + { + if (!class_exists(VersionHistory::class)) { + $this->markTestSkipped('package-versions is not installed.'); + } + + $this->ensureExecutor(); + $name = 'unchanged-deploy-with-draft'; + $code = ' 1];'; + $summary = 'Redeploy unchanged payload'; + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => $code, + 'name' => $name, + ])->assertOk(); + + $script = Script::where('title', $name)->firstOrFail(); + $publishedVersionId = (int) $script->versions()->published()->max('id'); + $script->saveDraft(); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => $code, + 'name' => $name, + 'version_name' => $summary, + ]) + ->assertOk() + ->assertJson(['action' => 'updated']); + + $this->assertSame( + $publishedVersionId, + (int) $script->versions()->published()->max('id') + ); + + $history = VersionHistory::query() + ->where('versionable_id', $publishedVersionId) + ->where('versionable_type', ScriptVersion::class) + ->orderByDesc('id') + ->first(); + + $this->assertNotNull($history); + $this->assertSame($summary, $history->subject); + } + + public function testDeployScriptUpdateStoresVersionName(): void + { + if (!class_exists(VersionHistory::class)) { + $this->markTestSkipped('package-versions is not installed.'); + } + + $this->ensureExecutor(); + $name = 'version-name-script-stored'; + $summary = 'Bump return payload'; + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' $name, + ])->assertOk(); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' $name, + 'version_name' => $summary, + ])->assertOk(); + + $script = Script::where('title', $name)->firstOrFail(); + $version = $script->versions()->orderByDesc('id')->first(); + $this->assertInstanceOf(ScriptVersion::class, $version); + + $history = VersionHistory::query() + ->where('versionable_id', $version->id) + ->where('versionable_type', ScriptVersion::class) + ->orderByDesc('id') + ->first(); + + $this->assertNotNull($history); + $this->assertSame($summary, $history->subject); + } + + public function testGetScriptPhpByNameReturnsPhpCode(): void + { + $code = " true];\n"; + $script = Script::factory()->create([ + 'title' => 'sample-get-script', + 'code' => $code, + 'run_as_user_id' => $this->user->id, + ]); + + $response = $this->actingAs($this->user, 'api') + ->get('/api/1.0' . self::GET_ENDPOINT . '?name=sample-get-script'); + + $response->assertStatus(200); + $this->assertStringContainsString('text/plain', (string) $response->headers->get('Content-Type')); + $this->assertSame((string) $script->id, $response->headers->get('X-Script-Id')); + $this->assertSame($code, $response->getContent()); + } + + public function testDeployScriptPrefersPhpExecutorOnCreate(): void + { + if (!ScriptExecutor::query()->where('language', 'php')->exists()) { + ScriptExecutor::factory()->create(['language' => 'php', 'title' => 'PHP Executor']); + } + + $executor = app(ScriptExecutorResolver::class)->resolveForNewScript(); + $this->assertNotNull($executor); + $this->assertSame('php', $executor->language); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'new-php-script', + 'description' => 'Merged migration script.', + ]) + ->assertStatus(200) + ->assertJson(['action' => 'created']); + + $script = Script::where('title', 'new-php-script')->first(); + $this->assertSame($executor->id, $script->script_executor_id); + $this->assertSame('Merged migration script.', $script->description); + } + + public function testDeployScriptCreatesWithRequestedExecutorId(): void + { + $first = $this->phpExecutor('First PHP Executor'); + $second = $this->phpExecutor('Second PHP Executor'); + $this->assertNotSame($first->id, $second->id); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-by-id-script', + 'script_executor_id' => $second->id, + ])->assertOk()->assertJson(['action' => 'created']); + + $this->assertSame($second->id, Script::where('title', 'executor-by-id-script')->value('script_executor_id')); + } + + public function testDeployScriptCreatesWithRequestedExecutorTitle(): void + { + $this->phpExecutor('First PHP Executor'); + $target = $this->phpExecutor('Target PHP Executor'); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-by-title-script', + 'script_executor_title' => 'Target PHP Executor', + ])->assertOk(); + + $this->assertSame($target->id, Script::where('title', 'executor-by-title-script')->value('script_executor_id')); + } + + public function testDeployScriptUpdateCanMoveScriptToRequestedExecutor(): void + { + $this->phpExecutor('First PHP Executor'); + $target = $this->phpExecutor('Target PHP Executor'); + $script = Script::factory()->create(['title' => 'executor-update-script', 'language' => 'php']); + $this->assertNotSame($target->id, $script->script_executor_id); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-update-script', + 'script_executor_id' => $target->id, + 'version_name' => 'Move to the plugin executor', + ])->assertOk()->assertJson(['action' => 'updated']); + + $this->assertSame($target->id, $script->refresh()->script_executor_id); + } + + public function testDeployScriptUpdateKeepsExecutorWhenNoneIsRequested(): void + { + $this->phpExecutor('First PHP Executor'); + $target = $this->phpExecutor('Target PHP Executor'); + $script = Script::factory()->create([ + 'title' => 'executor-kept-script', + 'language' => 'php', + 'script_executor_id' => $target->id, + ]); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-kept-script', + 'version_name' => 'Change the code only', + ])->assertOk(); + + $this->assertSame($target->id, $script->refresh()->script_executor_id); + } + + public function testDeployScriptRejectsUnknownExecutor(): void + { + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-unknown-script', + 'script_executor_id' => 999999, + ]) + ->assertStatus(422) + ->assertJson(['success' => false]) + ->assertJsonValidationErrors(['script_executor_id']); + + $this->assertNull(Script::where('title', 'executor-unknown-script')->first()); + } + + public function testDeployScriptRejectsExecutorOfAnotherLanguage(): void + { + $lua = ScriptExecutor::factory()->create(['language' => 'lua', 'title' => 'Lua Executor']); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-wrong-language-script', + 'script_executor_title' => $lua->title, + ]) + ->assertStatus(422) + ->assertJsonValidationErrors(['script_executor_title']); + + $this->assertNull(Script::where('title', 'executor-wrong-language-script')->first()); + } + + public function testNonAdminWithoutEditScriptsCannotChooseExecutor(): void + { + $default = $this->phpExecutor('Default PHP Executor'); + $this->actAsNonAdmin([]); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-forbidden-create', + 'script_executor_id' => $default->id, + ])->assertStatus(403)->assertJson(['success' => false]); + + $this->assertNull(Script::where('title', 'executor-forbidden-create')->first()); + } + + public function testNonAdminCannotMoveScriptToNonDefaultExecutor(): void + { + $this->phpExecutor('Default PHP Executor'); + $admin = $this->phpExecutor('Admin PHP Executor'); + $script = Script::factory()->create(['title' => 'executor-forbidden-update', 'language' => 'php']); + $before = $script->script_executor_id; + $this->actAsNonAdmin(['edit-scripts']); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-forbidden-update', + 'script_executor_id' => $admin->id, + 'version_name' => 'Move to the admin executor', + ])->assertStatus(403)->assertJson(['success' => false]); + + $this->assertSame($before, $script->refresh()->script_executor_id); + } + + public function testNonAdminCannotUseCustomExecutor(): void + { + $default = $this->phpExecutor('Default PHP Executor'); + $default->update(['type' => 'custom']); + $this->actAsNonAdmin(['edit-scripts']); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-forbidden-custom', + 'script_executor_id' => $default->id, + ])->assertStatus(403); + + $this->assertNull(Script::where('title', 'executor-forbidden-custom')->first()); + } + + public function testNonAdminWithEditScriptsCanUseDefaultExecutor(): void + { + $default = ScriptExecutor::query()->where('language', 'php')->orderBy('id')->first() + ?? $this->phpExecutor('Default PHP Executor'); + $this->actAsNonAdmin(['edit-scripts']); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-allowed-default', + 'script_executor_id' => $default->id, + ])->assertOk()->assertJson(['action' => 'created']); + + $this->assertSame($default->id, Script::where('title', 'executor-allowed-default')->value('script_executor_id')); + } + + public function testNonAdminWithoutExecutorKeepsCurrentBehavior(): void + { + $this->ensureExecutor(); + $this->actAsNonAdmin([]); + + $this->apiCall('POST', self::API_ENDPOINT, [ + 'code' => ' 'executor-none-requested', + ])->assertOk()->assertJson(['action' => 'created']); + } + + /** + * Make the authenticated user a regular user holding only the given permissions. + */ + private function actAsNonAdmin(array $permissions): void + { + $this->user->is_administrator = false; + $this->user->save(); + $this->initializePermissions(); + + foreach ($permissions as $permission) { + $this->user->permissions()->attach(Permission::byName($permission)->id); + } + $this->user->refresh(); + $this->flushSession(); + } + + private function phpExecutor(string $title): ScriptExecutor + { + return ScriptExecutor::factory()->create(['language' => 'php', 'title' => $title]); + } + + private function ensureExecutor(): ScriptExecutor + { + return ScriptExecutor::query()->first() ?? ScriptExecutor::factory()->create(); + } +} diff --git a/tests/Feature/Api/OAuthTest.php b/tests/Feature/Api/OAuthTest.php index 491609ee30..c3c23bb0f2 100644 --- a/tests/Feature/Api/OAuthTest.php +++ b/tests/Feature/Api/OAuthTest.php @@ -11,6 +11,7 @@ class OAuthTest extends TestCase use RequestHelper; private const OAUTH_CLIENTS_URL = '/oauth/clients'; + private const OAUTH_CLIENT_URL = '/oauth/clients/'; public $json = null; diff --git a/tests/Feature/Api/PluginsTest.php b/tests/Feature/Api/PluginsTest.php new file mode 100644 index 0000000000..e800d384c4 --- /dev/null +++ b/tests/Feature/Api/PluginsTest.php @@ -0,0 +1,127 @@ +apiCall('POST', '/plugins/install', [ + 'url' => 'https://github.com/ProcessMaker/package-translations.git', + 'branch' => 'develop', + ]); + + $response->assertStatus(200); + $response->assertJson([ + 'queued' => true, + 'message' => 'Plugin installation queued', + ]); + + Bus::assertDispatched(InstallPlugin::class, function (InstallPlugin $job) { + return $job->userId === $this->user->id + && $job->url === 'https://github.com/ProcessMaker/package-translations.git' + && $job->branch === 'develop' + && $job->tag === null + && $job->zipPath === null + && $job->gitUsername === null + && $job->gitToken === null + && $job->timeout >= 600; + }); + } + + public function testUninstallQueuesJob(): void + { + Bus::fake([UninstallPlugin::class]); + + $response = $this->apiCall('DELETE', '/plugins/package-translations'); + + $response->assertStatus(200); + $response->assertJson(['queued' => true]); + + Bus::assertDispatched(UninstallPlugin::class, function (UninstallPlugin $job) { + return $job->pluginName === 'package-translations' + && $job->userId === $this->user->id; + }); + } + + public function testToggleQueuesJob(): void + { + Bus::fake([TogglePlugin::class]); + + $response = $this->apiCall('PATCH', '/plugins/package-translations/toggle'); + + $response->assertStatus(200); + $response->assertJson(['queued' => true]); + + Bus::assertDispatched(TogglePlugin::class, function (TogglePlugin $job) { + return $job->pluginName === 'package-translations' + && $job->userId === $this->user->id; + }); + } + + public function testInstallRejectsNonHttpsUrl(): void + { + // The https-only rule is enforced in production only. + config(['app.env' => 'production']); + Bus::fake([InstallPlugin::class]); + + $response = $this->apiCall('POST', '/plugins/install', [ + 'url' => storage_path('plugins'), + ]); + + $response->assertStatus(422); + Bus::assertNotDispatched(InstallPlugin::class); + } + + public function testReinstallQueuesJobWithBranchAndGitCredentials(): void + { + Bus::fake([ReinstallPlugin::class]); + + $response = $this->apiCall('POST', '/plugins/package-translations/reinstall', [ + 'branch' => 'develop', + 'git_username' => 'deploy-user', + 'git_token' => 'ghp_test_token', + ]); + + $response->assertStatus(200); + $response->assertJson([ + 'queued' => true, + 'message' => 'Plugin reinstall queued', + ]); + + Bus::assertDispatched(ReinstallPlugin::class, function (ReinstallPlugin $job) { + return $job->pluginName === 'package-translations' + && $job->userId === $this->user->id + && $job->branch === 'develop' + && $job->tag === null + && $job->gitUsername === 'deploy-user' + && $job->gitToken === 'ghp_test_token'; + }); + } + + public function testInstallRejectsBranchAndTagTogether(): void + { + Bus::fake([InstallPlugin::class]); + + $response = $this->apiCall('POST', '/plugins/install', [ + 'url' => 'https://github.com/ProcessMaker/package-translations.git', + 'branch' => 'develop', + 'tag' => 'v1.0.0', + ]); + + $response->assertStatus(422); + Bus::assertNotDispatched(InstallPlugin::class); + } +} diff --git a/tests/Feature/Api/RequestFileUploadTest.php b/tests/Feature/Api/RequestFileUploadTest.php index 15446b8696..992cf11529 100644 --- a/tests/Feature/Api/RequestFileUploadTest.php +++ b/tests/Feature/Api/RequestFileUploadTest.php @@ -28,7 +28,7 @@ class RequestFileUploadTest extends TestCase protected $task; /** - * @var \ProcessMaker\Models\User[] + * @var User[] */ protected $assigned = []; diff --git a/tests/Feature/Api/ScreenTest.php b/tests/Feature/Api/ScreenTest.php index d6b15608b3..c6455de761 100644 --- a/tests/Feature/Api/ScreenTest.php +++ b/tests/Feature/Api/ScreenTest.php @@ -299,6 +299,13 @@ public function testUpdateDraftScreen() 'computed' => [['id' => 2, 'name' => 'test', 'type' => 'expression', 'formula' => 'test', 'property' => 'test']], 'custom_css' => '.class { font-size: large; }', 'watchers' => '[{"input_data":"{}","script_configuration":"{}","synchronous":false,"show_async_loading":false,"run_onload":false,"name":"Watchers","watching":"form_input_1","script":{"id":"script-4","uuid":"98a4376e-efb8-4c10-83fd-01199398eddc","key":null,"title":"Autosave","description":"Autosave","language":"php","code":"","timeout":60,"run_as_user_id":1,"status":"ACTIVE","script_category_id":"1","script_executor_id":3},"script_id":"4","script_key":null,"uid":"16794186944621"}]', + 'preview_presets' => [ + [ + 'title' => 'Empty contact', + // data stored as JSON string so empty objects ({}) survive PHP json_decode + 'data' => '{"email":"jane@example.com","contact":{}}', + ], + ], 'type' => $screen->type, 'screen_category_id' => $screen->screen_category_id, ]); @@ -313,6 +320,15 @@ public function testUpdateDraftScreen() $this->assertEquals($draft->computed, [['id' => 2, 'name' => 'test', 'type' => 'expression', 'formula' => 'test', 'property' => 'test']]); $this->assertEquals($draft->custom_css, '.class { font-size: large; }'); $this->assertEquals($draft->watchers, '[{"input_data":"{}","script_configuration":"{}","synchronous":false,"show_async_loading":false,"run_onload":false,"name":"Watchers","watching":"form_input_1","script":{"id":"script-4","uuid":"98a4376e-efb8-4c10-83fd-01199398eddc","key":null,"title":"Autosave","description":"Autosave","language":"php","code":"","timeout":60,"run_as_user_id":1,"status":"ACTIVE","script_category_id":"1","script_executor_id":3},"script_id":"4","script_key":null,"uid":"16794186944621"}]'); + $this->assertEquals( + [ + [ + 'title' => 'Empty contact', + 'data' => '{"email":"jane@example.com","contact":{}}', + ], + ], + $draft->preview_presets + ); $this->assertLessThan(3, $draft->updated_at->diffInSeconds($screen->updated_at)); } diff --git a/tests/Feature/Api/ScriptsTest.php b/tests/Feature/Api/ScriptsTest.php index 508196c364..bbccc80d33 100644 --- a/tests/Feature/Api/ScriptsTest.php +++ b/tests/Feature/Api/ScriptsTest.php @@ -29,6 +29,8 @@ class ScriptsTest extends TestCase { use RequestHelper; + public $withPermissions = true; + const API_TEST_SCRIPT = '/scripts'; const STRUCTURE = [ @@ -425,6 +427,185 @@ public function testPreviewScriptFail() }); } + /** + * Preview via Core Service Task in-process runner when allow_in_process is set. + */ + public function testPreviewScriptInProcess() + { + config(['core-service-task.enabled' => true]); + $this->withPersonalAccessClient(); + + Event::fake([ + ScriptResponseEvent::class, + ]); + + $script = $this->getScript('php'); + $script->allow_in_process = true; + $script->saveOrFail(); + + $url = route('api.scripts.preview', $script->id); + $response = $this->apiCall('POST', $url, [ + 'data' => '{"ping":"1"}', + 'code' => ' $data["ping"]];', + 'nonce' => 'in-process-nonce', + ]); + $response->assertStatus(200); + $response->assertJson(['status' => 'success', 'run_in_process' => true]); + + Event::assertDispatched(ScriptResponseEvent::class, function ($event) { + return ($event->response['output']['pong'] ?? null) === '1' + && $event->nonce === 'in-process-nonce'; + }); + } + + /** + * Explicit run_in_process request flag for preview (before saving allow_in_process). + */ + public function testPreviewScriptInProcessWithRequestFlag() + { + config(['core-service-task.enabled' => true]); + $this->withPersonalAccessClient(); + + Event::fake([ + ScriptResponseEvent::class, + ]); + + $script = $this->getScript('php'); + $script->allow_in_process = false; + $script->saveOrFail(); + + $url = route('api.scripts.preview', $script->id); + $response = $this->apiCall('POST', $url, [ + 'data' => '{}', + 'code' => ' "flag"];', + 'nonce' => 'flag-nonce', + 'run_in_process' => true, + ]); + $response->assertStatus(200); + $response->assertJson(['run_in_process' => true]); + + Event::assertDispatched(ScriptResponseEvent::class, function ($event) { + return ($event->response['output']['via'] ?? null) === 'flag' + && $event->nonce === 'flag-nonce'; + }); + } + + public function testAdminCanSelectModulesExecutionMode(): void + { + config([ + 'core-service-task.enabled' => true, + 'core-service-task.modules_enabled' => true, + ]); + + $script = $this->getScript('php'); + $response = $this->apiCall('PUT', route('api.scripts.update', $script), [ + 'title' => $script->title, + 'language' => 'php', + 'code' => $script->code, + 'description' => $script->description, + 'run_as_user_id' => $script->run_as_user_id, + 'script_executor_id' => $script->script_executor_id, + 'script_category_id' => $script->script_category_id, + 'allow_in_process' => true, + 'execution_mode' => Script::EXECUTION_MODE_MODULES, + ]); + + $response->assertNoContent(); + $this->assertSame( + Script::EXECUTION_MODE_MODULES, + $script->refresh()->execution_mode + ); + } + + public function testNonPrivilegedUserFallsBackToBareWhenSelectingModules(): void + { + $editor = User::factory()->create(['is_administrator' => false]); + $editor->giveDirectPermission('edit-scripts'); + $script = $this->getScript('php'); + + $response = $this->actingAs($editor, 'api')->putJson( + route('api.scripts.update', $script), + [ + 'title' => $script->title, + 'language' => 'php', + 'code' => $script->code, + 'description' => $script->description, + 'run_as_user_id' => $script->run_as_user_id, + 'script_executor_id' => $script->script_executor_id, + 'script_category_id' => $script->script_category_id, + 'allow_in_process' => true, + 'execution_mode' => Script::EXECUTION_MODE_MODULES, + ] + ); + + $response->assertNoContent(); + $this->assertSame( + Script::EXECUTION_MODE_BARE, + $script->refresh()->execution_mode + ); + } + + public function testNonPrivilegedUserEditingModulesScriptFallsBackToBare(): void + { + $editor = User::factory()->create(['is_administrator' => false]); + $editor->giveDirectPermission('edit-scripts'); + $editor->giveDirectPermission('create-scripts'); + $script = $this->getScript('php'); + $script->update([ + 'allow_in_process' => true, + 'execution_mode' => Script::EXECUTION_MODE_MODULES, + ]); + + $response = $this->actingAs($editor, 'api')->putJson( + route('api.scripts.update', $script), + [ + 'title' => 'Updated without modules', + 'language' => 'php', + 'code' => $script->code, + 'description' => $script->description, + 'run_as_user_id' => $script->run_as_user_id, + 'script_executor_id' => $script->script_executor_id, + 'script_category_id' => $script->script_category_id, + 'allow_in_process' => true, + ] + ); + + $response->assertNoContent(); + $this->assertSame( + Script::EXECUTION_MODE_BARE, + $script->refresh()->execution_mode + ); + } + + public function testNonPrivilegedUserDuplicatesModulesScriptAsBare(): void + { + $editor = User::factory()->create(['is_administrator' => false]); + $editor->giveDirectPermission('edit-scripts'); + $editor->giveDirectPermission('create-scripts'); + $script = $this->getScript('php'); + $script->update([ + 'allow_in_process' => true, + 'execution_mode' => Script::EXECUTION_MODE_MODULES, + ]); + + $response = $this->actingAs($editor, 'api')->putJson( + route('api.scripts.duplicate', $script), + [ + 'title' => 'Duplicate without modules', + 'language' => 'php', + 'description' => $script->description, + 'run_as_user_id' => $script->run_as_user_id, + 'script_category_id' => $script->script_category_id, + ] + ); + + $response->assertCreated(); + $this->assertSame( + Script::EXECUTION_MODE_BARE, + Script::findOrFail($response->json('id'))->execution_mode + ); + } + /** * A user with only view-scripts must not be able to run arbitrary code through preview (FOUR-34242) */ diff --git a/tests/Feature/Api/TaskAssignmentPreviousOwnerTest.php b/tests/Feature/Api/TaskAssignmentPreviousOwnerTest.php index ea87216196..1852b96726 100644 --- a/tests/Feature/Api/TaskAssignmentPreviousOwnerTest.php +++ b/tests/Feature/Api/TaskAssignmentPreviousOwnerTest.php @@ -25,7 +25,7 @@ class TaskAssignmentPreviousOwnerTest extends TestCase protected $task; /** - * @var \ProcessMaker\Models\User + * @var User */ protected $assigned; @@ -109,10 +109,10 @@ public function testSingleUserAssignment() /** * Complete task * - * @param \ProcessMaker\Models\ProcessRequestToken $task + * @param ProcessRequestToken $task * @param array $data * - * @return \ProcessMaker\Models\ProcessRequestToken + * @return ProcessRequestToken */ private function completeTask(ProcessRequestToken $task, $data = []) { diff --git a/tests/Feature/Api/TaskLockAssignmentTest.php b/tests/Feature/Api/TaskLockAssignmentTest.php index c312e5c3aa..2abb4af07e 100644 --- a/tests/Feature/Api/TaskLockAssignmentTest.php +++ b/tests/Feature/Api/TaskLockAssignmentTest.php @@ -17,12 +17,12 @@ class TaskLockAssignmentTest extends TestCase use RequestHelper; /** - * @var \ProcessMaker\Models\User + * @var User */ protected $user1; /** - * @var \ProcessMaker\Models\User + * @var User */ protected $user2; @@ -160,10 +160,10 @@ public function testWithNoLockAssignment() /** * Complete task * - * @param \ProcessMaker\Models\ProcessRequestToken $task + * @param ProcessRequestToken $task * @param array $data * - * @return \ProcessMaker\Models\ProcessRequestToken + * @return ProcessRequestToken */ private function completeTask(ProcessRequestToken $task, $data = []) { diff --git a/tests/Feature/Api/V1_1/CaseUtilsTest.php b/tests/Feature/Api/V1_1/CaseUtilsTest.php index b8be5d38a5..d0f3df3a60 100644 --- a/tests/Feature/Api/V1_1/CaseUtilsTest.php +++ b/tests/Feature/Api/V1_1/CaseUtilsTest.php @@ -123,8 +123,8 @@ public function test_store_participants_with_empty_data() public function test_extract_data_process() { - $object = (object)[ - 'process' => (object)[ + $object = (object) [ + 'process' => (object) [ 'id' => 1, 'name' => 'Process 1', ], @@ -138,11 +138,11 @@ public function test_extract_data_process() public function test_extract_data_request() { - $object = (object)[ - 'processRequest' => (object)[ + $object = (object) [ + 'processRequest' => (object) [ 'id' => 1, 'name' => 'Request 1', - 'parentRequest' => (object)[ + 'parentRequest' => (object) [ 'id' => 2, ], ], @@ -157,7 +157,7 @@ public function test_extract_data_request() public function test_extract_data_task() { - $object = (object)[ + $object = (object) [ 'id' => 1, 'element_id' => 101, 'element_name' => 'Task 1', diff --git a/tests/Feature/Cases/CaseSyncRepositoryTest.php b/tests/Feature/Cases/CaseSyncRepositoryTest.php index c91cd2b4fa..7eef39f43f 100644 --- a/tests/Feature/Cases/CaseSyncRepositoryTest.php +++ b/tests/Feature/Cases/CaseSyncRepositoryTest.php @@ -2,11 +2,11 @@ namespace Tests\Feature\Cases; -use ProcessMaker\Repositories\CaseSyncRepository; +use Illuminate\Support\Facades\DB; use ProcessMaker\Models\ProcessRequest; use ProcessMaker\Models\ProcessRequestToken; +use ProcessMaker\Repositories\CaseSyncRepository; use Tests\TestCase; -use Illuminate\Support\Facades\DB; class CaseSyncRepositoryTest extends TestCase { @@ -24,7 +24,7 @@ public function testSyncCases() 'status' => 'ACTIVE', 'element_id' => 'task-1', 'process_request_id' => $processRequest1->id, - 'process_id' => $processRequest1->process_id + 'process_id' => $processRequest1->process_id, ])->toArray(), ProcessRequestToken::factory()->make([ 'element_name' => 'Task 2', @@ -32,7 +32,7 @@ public function testSyncCases() 'status' => 'CLOSED', 'element_id' => 'task-2', 'process_request_id' => $processRequest1->id, - 'process_id' => $processRequest1->process_id + 'process_id' => $processRequest1->process_id, ])->toArray(), ProcessRequestToken::factory()->make([ 'element_name' => 'Task 3', @@ -40,7 +40,7 @@ public function testSyncCases() 'status' => 'ACTIVE', 'element_id' => 'call-activity-1', 'process_request_id' => $processRequest1->id, - 'process_id' => $processRequest1->process_id + 'process_id' => $processRequest1->process_id, ])->toArray(), ]); @@ -51,7 +51,7 @@ public function testSyncCases() 'status' => 'CLOSED', 'element_id' => 'task-4', 'process_request_id' => $processRequest2->id, - 'process_id' => $processRequest2->process_id + 'process_id' => $processRequest2->process_id, ])->toArray(), ProcessRequestToken::factory()->make([ 'element_name' => 'Task 5', @@ -59,7 +59,7 @@ public function testSyncCases() 'status' => 'ACTIVE', 'element_id' => 'task-5', 'process_request_id' => $processRequest2->id, - 'process_id' => $processRequest2->process_id + 'process_id' => $processRequest2->process_id, ])->toArray(), ]); @@ -85,21 +85,21 @@ public function testSyncCases() 'name' => 'Task 5', 'status' => 'ACTIVE', 'element_id' => 'task-5', - 'process_id' => $processRequest2->process_id + 'process_id' => $processRequest2->process_id, ], [ 'id' => $processRequest1->tokens()->where('element_id', 'task-2')->first()->id, 'name' => 'Task 2', 'status' => 'CLOSED', 'element_id' => 'task-2', - 'process_id' => $processRequest1->process_id + 'process_id' => $processRequest1->process_id, ], [ 'id' => $processRequest1->tokens()->where('element_id', 'task-1')->first()->id, 'name' => 'Task 1', 'status' => 'ACTIVE', 'element_id' => 'task-1', - 'process_id' => $processRequest1->process_id + 'process_id' => $processRequest1->process_id, ], ]; $expectedParticipants = [ diff --git a/tests/Feature/ConditionalRedirect/ConditionalRedirectTest.php b/tests/Feature/ConditionalRedirect/ConditionalRedirectTest.php index e1a5384209..0e01ff91a0 100644 --- a/tests/Feature/ConditionalRedirect/ConditionalRedirectTest.php +++ b/tests/Feature/ConditionalRedirect/ConditionalRedirectTest.php @@ -174,7 +174,7 @@ private function conditionalRedirectTest(array $requestData, array $expectedElem [ 'tokenId' => $tasks[0]['id'], 'nodeId' => $tasks[0]['element_id'], - ] + ], ], ]; $dispatched[] = $expectedEvent; @@ -203,7 +203,7 @@ private function conditionalRedirectTest(array $requestData, array $expectedElem 'params' => [ [ 'tokenId' => $tasks[0]['id'], - ] + ], ], ]; $dispatched[] = $expectedEvent; @@ -218,6 +218,7 @@ private function getActiveTasks() //Get the active tasks of the request $route = route('api.tasks.index', ['status' => 'ACTIVE']); $response = $this->apiCall('GET', $route); + return $response->json('data'); } @@ -225,6 +226,7 @@ private function getTaskById($id) { $route = route('api.tasks.show', [$id, 'include' => 'data,elementDestination']); $response = $this->apiCall('GET', $route); + return $response->json(); } } diff --git a/tests/Feature/Console/PluginReloadListenCommandTest.php b/tests/Feature/Console/PluginReloadListenCommandTest.php new file mode 100644 index 0000000000..8d6f4005f5 --- /dev/null +++ b/tests/Feature/Console/PluginReloadListenCommandTest.php @@ -0,0 +1,222 @@ +previousSocketTimeout = (string) ini_get('default_socket_timeout'); + $this->stateFile = sys_get_temp_dir() . '/pm-plugin-reload-' . uniqid(); + config([ + 'plugin_manager.supervisorctl_bin' => 'supervisorctl', + 'plugin_manager.supervisorctl_config' => null, + 'plugin_manager.supervisor_restart_target' => 'all', + 'plugin_manager.supervisor_restart_delay' => 5, + 'plugin_manager.reload_channel' => 'plugin-runtime-reload', + 'plugin_manager.reload_version_key' => 'plugin-runtime-reload:version', + 'plugin_manager.reload_state_file' => $this->stateFile, + 'plugin_manager.reload_reconnect_delay' => 0, + 'plugin_manager.reload_listen_max_cycles' => 1, + ]); + } + + protected function tearDown(): void + { + ini_set('default_socket_timeout', $this->previousSocketTimeout); + + if (is_file($this->stateFile)) { + unlink($this->stateFile); + } + + parent::tearDown(); + } + + private function expectSubscriptionClient(): void + { + $client = \Mockery::mock(); + $client->shouldReceive('setOption') + ->with(\Redis::OPT_READ_TIMEOUT, -1) + ->andReturnTrue(); + + $connection = \Mockery::mock(); + $connection->shouldReceive('client')->andReturn($client); + + Redis::shouldReceive('connection')->andReturn($connection); + } + + public function testListenerCatchesUpWhenAReloadWasMissed(): void + { + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + $this->expectSubscriptionClient(); + Redis::shouldReceive('get') + ->once() + ->with('plugin-runtime-reload:version') + ->andReturn('4'); + Redis::shouldReceive('subscribe') + ->once() + ->with(['test:plugin-runtime-reload'], \Mockery::type('Closure')); + + $this->artisan('plugin:reload-listen')->assertOk(); + + $this->assertSame('4', file_get_contents($this->stateFile)); + Process::assertRan(function ($process) { + $command = is_array($process->command) ? implode(' ', $process->command) : (string) $process->command; + + return str_contains($command, 'nohup') + && str_contains($command, 'supervisorctl') + && str_contains($command, 'restart') + && str_contains($command, 'all'); + }); + } + + public function testListenerSchedulesRestartForANewMessageAndSkipsTheSameVersion(): void + { + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + file_put_contents($this->stateFile, '2'); + + $this->expectSubscriptionClient(); + Redis::shouldReceive('get')->once()->andReturn('2'); + Redis::shouldReceive('subscribe') + ->once() + ->andReturnUsing(function (array $channels, \Closure $callback): void { + $this->assertSame(['test:plugin-runtime-reload'], $channels); + $callback(json_encode(['version' => 3, 'plugin' => 'package-plg']), 'plugin-runtime-reload'); + $callback(json_encode(['version' => 3, 'plugin' => 'package-plg']), 'plugin-runtime-reload'); + }); + + $this->artisan('plugin:reload-listen')->assertOk(); + + $this->assertSame('3', file_get_contents($this->stateFile)); + Process::assertRanTimes(function ($process) { + $command = is_array($process->command) ? implode(' ', $process->command) : (string) $process->command; + + return str_contains($command, 'supervisorctl'); + }, 1); + } + + public function testPublishStoresTheVersionAndNotifiesTheChannel(): void + { + Redis::shouldReceive('incr') + ->once() + ->with('plugin-runtime-reload:version') + ->andReturn(7); + Redis::shouldReceive('publish') + ->once() + ->withArgs(function (string $channel, string $message): bool { + $payload = json_decode($message, true); + + return $channel === 'test:plugin-runtime-reload' + && $payload['version'] === 7 + && $payload['plugin'] === 'package-plg' + && $payload['tenant_id'] === null; + }) + ->andReturn(1); + + $version = (new PluginRuntimeReload())->publish('package-plg'); + + $this->assertSame(7, $version); + } + + public function testChannelAndVersionKeyUseGlobalRedisScope(): void + { + config([ + 'database.redis.options.prefix' => 'instance:', + 'plugin_manager.reload_channel' => 'plugin-runtime-reload', + 'plugin_manager.reload_version_key' => 'plugin-runtime-reload:version', + 'plugin_manager.reload_state_file' => '/tmp/processmaker-plugin-reload-version', + ]); + app()->instance('currentTenant', new class { + public function getKey(): int + { + return 9; + } + }); + + $reload = new PluginRuntimeReload(); + + $this->assertSame('instance:plugin-runtime-reload', $reload->channel()); + $this->assertSame('plugin-runtime-reload:version', $reload->versionKey()); + $this->assertSame('/tmp/processmaker-plugin-reload-version', $reload->stateFile()); + } + + public function testListenerRestartsOnlyTheTenantFromThePayload(): void + { + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + file_put_contents($this->stateFile, '2'); + + $this->expectSubscriptionClient(); + Redis::shouldReceive('get')->once()->andReturn('2'); + Redis::shouldReceive('subscribe') + ->once() + ->andReturnUsing(function (array $channels, \Closure $callback): void { + $this->assertSame(['test:plugin-runtime-reload'], $channels); + $callback(json_encode([ + 'version' => 3, + 'plugin' => 'package-plg', + 'tenant_id' => 2, + ]), 'plugin-runtime-reload'); + }); + + $this->artisan('plugin:reload-listen')->assertOk(); + + $this->assertSame('3', file_get_contents($this->stateFile)); + Process::assertRan(function ($process) { + $command = is_array($process->command) ? implode(' ', $process->command) : (string) $process->command; + + return str_contains($command, 'supervisorctl') + && str_contains($command, 'restart') + && str_contains($command, 'octane-tenant-2:*'); + }); + } + + public function testListenerReconnectsAfterRedisReadError(): void + { + config(['plugin_manager.reload_listen_max_cycles' => 2]); + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + file_put_contents($this->stateFile, '4'); + + $this->expectSubscriptionClient(); + Redis::shouldReceive('get')->twice()->andReturn('4', '5'); + Redis::shouldReceive('purge')->once()->with('default'); + Redis::shouldReceive('subscribe') + ->twice() + ->andReturnUsing(function (): void { + static $attempt = 0; + $attempt++; + if ($attempt === 1) { + throw new \RedisException('read error on connection to 127.0.0.1:6379'); + } + }); + + $this->artisan('plugin:reload-listen') + ->expectsOutputToContain('Reconnecting.') + ->assertOk(); + + $this->assertSame('5', file_get_contents($this->stateFile)); + Process::assertRanTimes(function ($process) { + $command = is_array($process->command) ? implode(' ', $process->command) : (string) $process->command; + + return str_contains($command, 'supervisorctl'); + }, 1); + } +} diff --git a/tests/Feature/EditDataTest.php b/tests/Feature/EditDataTest.php index 1c2011fb1b..1c3b618b34 100644 --- a/tests/Feature/EditDataTest.php +++ b/tests/Feature/EditDataTest.php @@ -103,7 +103,7 @@ private function addProcessPermission(Process $process, array $users, array $gro * * @param User $userAssigned * - * @return \ProcessMaker\Models\Process + * @return Process */ private function createSingleTaskProcessUserAssignment(User $userAssigned) { @@ -132,7 +132,7 @@ private function createSingleTaskProcessUserAssignment(User $userAssigned) /** * Start a process * - * @param \ProcessMaker\Models\Process $process + * @param Process $process * @param string $startEvent * @param array $data * @@ -149,10 +149,10 @@ private function startProcess($process, $startEvent, $data = []) /** * Complete task * - * @param \ProcessMaker\Models\ProcessRequestToken $task + * @param ProcessRequestToken $task * @param array $data * - * @return \ProcessMaker\Models\ProcessRequestToken + * @return ProcessRequestToken */ private function completeTask(ProcessRequestToken $task, $data = []) { diff --git a/tests/Feature/ImportExport/Exporters/ProcessExporterWithScreenDataSourceTest.php b/tests/Feature/ImportExport/Exporters/ProcessExporterWithScreenDataSourceTest.php index f02fc39898..41a2657de5 100644 --- a/tests/Feature/ImportExport/Exporters/ProcessExporterWithScreenDataSourceTest.php +++ b/tests/Feature/ImportExport/Exporters/ProcessExporterWithScreenDataSourceTest.php @@ -24,7 +24,7 @@ public function testProcessExportWithScreenDataSource() // Create a script first to consume some IDs $script = Script::factory()->create(['title' => 'A Script']); - + $category = new $dataSourceCategoryClass(); $category->name = 'Test Category ' . uniqid(); $category->save(); @@ -68,12 +68,12 @@ public function testProcessExportWithScreenDataSource() $process = Process::factory()->create([ 'name' => 'Process with screen using data source', - 'bpmn' => $bpmn + 'bpmn' => $bpmn, ]); $exportJob = new ExportProcess($process); $exportJob->handle(); - + // Access private package property via reflection $reflection = new \ReflectionClass($exportJob); $property = $reflection->getProperty('package'); @@ -90,7 +90,7 @@ public function testProcessExportWithScreenDataSource() $this->assertNotEquals('data_source-' . $dataSource->id, $script['id']); $this->assertNotEquals($dataSource->id, $script['id']); // Also check that it's not present as a numeric ID if it's the same - if (is_numeric($script['id']) && (int)$script['id'] === $dataSource->id) { + if (is_numeric($script['id']) && (int) $script['id'] === $dataSource->id) { $this->fail('Data source ID ' . $dataSource->id . ' found in scripts section'); } } diff --git a/tests/Feature/ImportExport/Exporters/ScriptExporterTest.php b/tests/Feature/ImportExport/Exporters/ScriptExporterTest.php index 437eb5e912..0cc411ead6 100644 --- a/tests/Feature/ImportExport/Exporters/ScriptExporterTest.php +++ b/tests/Feature/ImportExport/Exporters/ScriptExporterTest.php @@ -62,7 +62,7 @@ public function testExportUncategorized() { DB::beginTransaction(); (new CategorySystemSeeder)->run(); - $uncategorizedCategory = \ProcessMaker\Models\ScriptCategory::first(); + $uncategorizedCategory = ScriptCategory::first(); $script = Script::factory()->create(['title' => 'test']); $script->categories()->sync([$uncategorizedCategory->id]); @@ -70,7 +70,7 @@ public function testExportUncategorized() DB::rollBack(); // Delete all created items since DB::beginTransaction (new CategorySystemSeeder)->run(); - $existingUncategorizedCategory = \ProcessMaker\Models\ScriptCategory::first(); + $existingUncategorizedCategory = ScriptCategory::first(); $existingUuid = $existingUncategorizedCategory->uuid; $this->import($payload); @@ -79,6 +79,46 @@ public function testExportUncategorized() $this->assertEquals($script->categories->first()->uuid, $existingUuid); } + public function testImportDowngradesModulesForUnauthorizedImportingUser(): void + { + $script = Script::factory()->create([ + 'title' => 'modules script', + 'language' => 'php', + 'allow_in_process' => true, + 'execution_mode' => Script::EXECUTION_MODE_MODULES, + ]); + $payload = $this->export($script, ScriptExporter::class); + $user = User::factory()->create(['is_administrator' => false]); + $options = new Options([ + $script->uuid => ['mode' => 'copy'], + ], $user->id); + + $this->import($payload, $options); + + $copy = Script::where('title', 'modules script 2')->firstOrFail(); + $this->assertSame(Script::EXECUTION_MODE_BARE, $copy->execution_mode); + } + + public function testImportPreservesModulesForAuthorizedImportingUser(): void + { + $script = Script::factory()->create([ + 'title' => 'authorized modules script', + 'language' => 'php', + 'allow_in_process' => true, + 'execution_mode' => Script::EXECUTION_MODE_MODULES, + ]); + $payload = $this->export($script, ScriptExporter::class); + $admin = User::where('is_administrator', true)->firstOrFail(); + $options = new Options([ + $script->uuid => ['mode' => 'copy'], + ], $admin->id); + + $this->import($payload, $options); + + $copy = Script::where('title', 'authorized modules script 2')->firstOrFail(); + $this->assertSame(Script::EXECUTION_MODE_MODULES, $copy->execution_mode); + } + public function testHiddenUsesParentMode() { $scriptCategory1 = ScriptCategory::factory()->create(['name' => 'test category A']); diff --git a/tests/Feature/ImportExport/Exporters/ScriptsInScreenDataSourceTest.php b/tests/Feature/ImportExport/Exporters/ScriptsInScreenDataSourceTest.php index f22ac082ce..e3ea31bf90 100644 --- a/tests/Feature/ImportExport/Exporters/ScriptsInScreenDataSourceTest.php +++ b/tests/Feature/ImportExport/Exporters/ScriptsInScreenDataSourceTest.php @@ -4,9 +4,9 @@ use ProcessMaker\Assets\DataSourcesInScreen; use ProcessMaker\Assets\ScriptsInScreen; +use ProcessMaker\Jobs\ExportScreen; use ProcessMaker\Models\Screen; use ProcessMaker\Models\Script; -use ProcessMaker\Jobs\ExportScreen; use Tests\TestCase; class ScriptsInScreenDataSourceTest extends TestCase @@ -101,7 +101,7 @@ public function testExportScreenIncludesDataSources() $exportJob = new ExportScreen($screen); $exportJob->handle(); - + // Access private package property via reflection $reflection = new \ReflectionClass($exportJob); // package is protected in ExportProcess diff --git a/tests/Feature/InterstitialTest.php b/tests/Feature/InterstitialTest.php index 5afb765ace..9545bb8a7e 100644 --- a/tests/Feature/InterstitialTest.php +++ b/tests/Feature/InterstitialTest.php @@ -45,6 +45,7 @@ private function loadProcess($file) { $data = []; $data['bpmn'] = Process::getProcessTemplate($file); + return Process::factory()->create($data); } @@ -56,6 +57,7 @@ private function importProcessPackage(string $file) $maxId = Process::max('id') ?? 0; $data = json_decode(file_get_contents(base_path('tests/Fixtures/' . $file)), true); $this->import($data); + return Process::where('id', '>', $maxId)->get(); } @@ -63,6 +65,7 @@ private function startProcess(Process $process, string $event, array $data = []) { $route = route('api.process_events.trigger', [$process->id, 'event' => $event]); $response = $this->apiCall('POST', $route, $data); + return $response->json(); } @@ -71,8 +74,10 @@ private function getActiveTasks() //Get the active tasks of the request $route = route('api.tasks.index', ['status' => 'ACTIVE']); $response = $this->apiCall('GET', $route); + return $response->json('data'); } + private function completeActiveTask(array $data = []) { //Get the active tasks of the request @@ -80,6 +85,7 @@ private function completeActiveTask(array $data = []) //Complete the task $route = route('api.tasks.update', [$tasks[0]['id'], 'status' => 'COMPLETED']); $response = $this->apiCall('PUT', $route, ['data' => $data]); + return $response->json(); } @@ -91,6 +97,7 @@ private function broadcastedTo(RedirectToEvent $event, array $expectedChannels): return false; } } + return true; } @@ -118,7 +125,7 @@ public function testExecuteProcessRedirects() [ 'tokenId' => $tasks[0]['id'], 'nodeId' => $tasks[0]['element_id'], - ] + ], ], ]; $dispatched[] = $expectedEvent; @@ -136,14 +143,13 @@ public function testExecuteProcessRedirects() 'params' => [ [ 'tokenId' => $tasks[0]['id'], - ] + ], ], ]; $dispatched[] = $expectedEvent; Event::assertDispatched(RedirectToEvent::class, function ($event) use ($expectedEvent) { return $event->method === $expectedEvent['method'] && $event->params[0]['tokenId'] === $expectedEvent['params'][0]['tokenId']; - }); // Complete active task (sub process - Task 2) and check RedirectToEvent dispatched to next Task not to subprocess summary @@ -154,12 +160,12 @@ public function testExecuteProcessRedirects() 'params' => [ [ 'tokenId' => $tasks[0]['id'], - ] + ], ], 'broadcastTo' => [ 'private-ProcessMaker.Models.ProcessRequest.' . $tasks[0]['process_request_id'], // active task: parent request 'private-ProcessMaker.Models.ProcessRequest.' . $task['process_request_id'], // completed task: child request - ] + ], ]; $dispatched[] = $expectedEvent; Event::assertDispatched(RedirectToEvent::class, function ($event) use ($expectedEvent, $task) { diff --git a/tests/Feature/Jobs/DevLinkInstallTest.php b/tests/Feature/Jobs/DevLinkInstallTest.php index 67cc45dd66..b08919a0da 100644 --- a/tests/Feature/Jobs/DevLinkInstallTest.php +++ b/tests/Feature/Jobs/DevLinkInstallTest.php @@ -6,8 +6,8 @@ use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Storage; use Mockery; -use ProcessMaker\Exception\DevLinkRemoteBundleException; use ProcessMaker\Events\ImportLog; +use ProcessMaker\Exception\DevLinkRemoteBundleException; use ProcessMaker\Jobs\DevLinkInstall; use ProcessMaker\Jobs\ImportV2; use ProcessMaker\Models\Bundle; diff --git a/tests/Feature/LoginRedirectTest.php b/tests/Feature/LoginRedirectTest.php index eb3b0800b2..4c80492c40 100644 --- a/tests/Feature/LoginRedirectTest.php +++ b/tests/Feature/LoginRedirectTest.php @@ -9,7 +9,6 @@ class LoginRedirectTest extends TestCase { /** - * * Test to verify that the login page redirects to the about page */ public function testLoginRedirect() @@ -25,7 +24,7 @@ public function testLoginRedirect() // Verify it redirects to the login page $response->assertRedirect('/login'); - // When we try to open the about page, we should be redirected to the login page + // When we try to open the about page, we should be redirected to the login page $response = $this->get(route('about.index')); $response->assertRedirect('/login'); @@ -50,7 +49,7 @@ public function testLoginRedirectWithDevtoolsOpeningMapFile() // Verify it redirects to the login page $response->assertRedirect('/login'); - // When we try to open the about page, we should be redirected to the login page + // When we try to open the about page, we should be redirected to the login page $response = $this->get(route('about.index')); $response->assertRedirect('/login'); diff --git a/tests/Feature/Mcp/DataConnectorsCollectionRecordsTest.php b/tests/Feature/Mcp/DataConnectorsCollectionRecordsTest.php new file mode 100644 index 0000000000..df0c9882d7 --- /dev/null +++ b/tests/Feature/Mcp/DataConnectorsCollectionRecordsTest.php @@ -0,0 +1,84 @@ + + */ + protected $connectionsToTransact = []; + + protected function setUp(): void + { + parent::setUp(); + + $this->user = User::factory()->create([ + 'password' => Hash::make('password'), + 'is_administrator' => true, + ]); + + if (!PackageHelper::isPackageInstalled(PackageHelper::PM_PACKAGE_COLLECTIONS)) { + $this->markTestSkipped('package-collections is not installed'); + } + } + + public function testAdminCanSeedCollectionRecords(): void + { + ProcessCategory::updateOrCreate( + ['name' => 'System'], + ['status' => 'ACTIVE', 'is_system' => true], + ); + + $createScreen = Screen::factory()->create(['title' => 'MCP Rec Create', 'type' => 'FORM', 'config' => [['items' => []]]]); + $readScreen = Screen::factory()->create(['title' => 'MCP Rec Read', 'type' => 'DISPLAY', 'config' => [['items' => []]]]); + $updateScreen = Screen::factory()->create(['title' => 'MCP Rec Update', 'type' => 'FORM', 'config' => [['items' => []]]]); + + $created = DataConnectorsServer::actingAs($this->user)->tool(CreateCollectionTool::class, [ + 'name' => 'MCP Records Collection', + 'description' => 'For record seeding', + 'create_screen_id' => $createScreen->id, + 'read_screen_id' => $readScreen->id, + 'update_screen_id' => $updateScreen->id, + ]); + $created->assertOk()->assertHasNoErrors()->assertSee('MCP Records Collection'); + + $collectionId = Collection::where('name', 'MCP Records Collection')->value('id'); + $this->assertNotNull($collectionId); + + DataConnectorsServer::actingAs($this->user)->tool(CreateCollectionRecordsTool::class, [ + 'collection_id' => $collectionId, + 'records' => [ + ['first_name' => 'Ada', 'last_name' => 'Lovelace'], + ['first_name' => 'Grace', 'last_name' => 'Hopper'], + ], + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('created_count', 2) + ->has('data', 2) + ->etc()); + + DataConnectorsServer::actingAs($this->user)->tool(ListCollectionRecordsTool::class, [ + 'collection_id' => $collectionId, + ])->assertOk()->assertSee('Ada'); + } +} diff --git a/tests/Feature/Mcp/DataConnectorsServerTest.php b/tests/Feature/Mcp/DataConnectorsServerTest.php new file mode 100644 index 0000000000..c99000da00 --- /dev/null +++ b/tests/Feature/Mcp/DataConnectorsServerTest.php @@ -0,0 +1,277 @@ + + */ + protected $connectionsToTransact = []; + + protected function setUp(): void + { + parent::setUp(); + + // RequestHelper::setUp is shadowed when this class defines setUp — recreate admin user. + $this->user = User::factory()->create([ + 'password' => Hash::make('password'), + 'is_administrator' => true, + ]); + + if (!PackageHelper::isPackageInstalled(PackageHelper::PM_PACKAGE_DATA_SOURCES)) { + $this->markTestSkipped('package-data-sources is not installed'); + } + if (!PackageHelper::isPackageInstalled(PackageHelper::PM_PACKAGE_COLLECTIONS)) { + $this->markTestSkipped('package-collections is not installed'); + } + } + + public function testAdminCanCreateListAndUpdateADataConnector(): void + { + $category = DataSourceCategory::factory()->create([ + 'status' => 'ACTIVE', + 'is_system' => false, + ]); + + $created = DataConnectorsServer::actingAs($this->user)->tool(CreateDataConnectorTool::class, [ + 'name' => 'MCP Demo API', + 'description' => 'Demo connector', + 'type' => 'REST', + 'authtype' => 'NONE', + 'data_source_category_id' => (string) $category->id, + 'api_base_url' => 'https://example.test', + 'endpoints' => [ + 'listItems' => [ + 'purpose' => 'listItems', + 'method' => 'GET', + 'url' => '{{__api_base_url__}}/items', + ], + ], + ]); + + $created->assertOk() + ->assertHasNoErrors() + ->assertSee('MCP Demo API') + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('name', 'MCP Demo API') + ->where('type', 'REST') + ->where('authtype', 'NONE') + ->has('endpoints.listItems') + ->etc()); + + $connector = DataSource::where('name', 'MCP Demo API')->firstOrFail(); + + DataConnectorsServer::actingAs($this->user)->tool(ListDataConnectorsTool::class, [ + 'filter' => 'MCP Demo', + ])->assertOk()->assertSee('MCP Demo API'); + + DataConnectorsServer::actingAs($this->user)->tool(ListDataConnectorCategoriesTool::class, [ + 'filter' => $category->name, + ])->assertOk()->assertSee($category->name); + + DataConnectorsServer::actingAs($this->user)->tool(GetDataConnectorTool::class, [ + 'id' => $connector->id, + ])->assertOk()->assertSee('listItems'); + + DataConnectorsServer::actingAs($this->user)->tool(UpdateDataConnectorTool::class, [ + 'id' => $connector->id, + 'description' => 'Updated demo connector', + ])->assertOk()->assertSee('Updated demo connector'); + + $this->assertSame('Updated demo connector', $connector->refresh()->description); + } + + public function testAdminCanCreateListAndUpdateACollection(): void + { + ProcessCategory::factory()->create([ + 'name' => 'System', + 'status' => 'ACTIVE', + 'is_system' => true, + ]); + + $createScreen = Screen::factory()->create(['title' => 'MCP Create', 'type' => 'FORM', 'config' => [['items' => []]]]); + $readScreen = Screen::factory()->create(['title' => 'MCP Read', 'type' => 'DISPLAY', 'config' => [['items' => []]]]); + $updateScreen = Screen::factory()->create(['title' => 'MCP Update', 'type' => 'FORM', 'config' => [['items' => []]]]); + + $created = DataConnectorsServer::actingAs($this->user)->tool(CreateCollectionTool::class, [ + 'name' => 'MCP Demo Collection', + 'description' => 'Collection for MCP tests', + 'create_screen_id' => $createScreen->id, + 'read_screen_id' => $readScreen->id, + 'update_screen_id' => $updateScreen->id, + ]); + + $created->assertOk() + ->assertHasNoErrors() + ->assertSee('MCP Demo Collection'); + + $collection = Collection::where('name', 'MCP Demo Collection')->firstOrFail(); + + DataConnectorsServer::actingAs($this->user)->tool(ListCollectionsTool::class, [ + 'filter' => 'MCP Demo Collection', + ])->assertOk()->assertSee('MCP Demo Collection'); + + DataConnectorsServer::actingAs($this->user)->tool(GetCollectionTool::class, [ + 'id' => $collection->id, + ])->assertOk()->assertSee('Collection for MCP tests'); + + DataConnectorsServer::actingAs($this->user)->tool(UpdateCollectionTool::class, [ + 'id' => $collection->id, + 'description' => 'Updated collection description', + ])->assertOk()->assertSee('Updated collection description'); + } + + public function testDataConnectorToolsRequirePermission(): void + { + DataConnectorsServer::tool(ListDataConnectorsTool::class) + ->assertHasErrors(['Authenticate with a ProcessMaker API token']); + + $member = User::factory()->create([ + 'is_administrator' => false, + ]); + + DataConnectorsServer::actingAs($member)->tool(ListDataConnectorsTool::class) + ->assertHasErrors(['view-data-sources']); + } + + public function testCreateRejectsEndpointWithoutPurposeKeyMatch(): void + { + $category = DataSourceCategory::factory()->create([ + 'status' => 'ACTIVE', + 'is_system' => false, + ]); + + DataConnectorsServer::actingAs($this->user)->tool(CreateDataConnectorTool::class, [ + 'name' => 'Bad Endpoint Map', + 'type' => 'REST', + 'authtype' => 'NONE', + 'data_source_category_id' => (string) $category->id, + 'endpoints' => [ + 'wrongKey' => [ + 'purpose' => 'listItems', + 'method' => 'GET', + 'url' => 'https://example.test/items', + ], + ], + ])->assertHasErrors(['map key must equal purpose']); + } + + public function testServerInstructionsIncludeDataConnectorCatalogWithoutSkillBodies(): void + { + $this->seedMcpGuidance(); + + $server = app(DataConnectorsServer::class, ['transport' => new FakeTransporter()]); + $instructions = $server->createContext()->instructions; + + $this->assertStringContainsString('get-mcp-guidance', $instructions); + $this->assertStringContainsString('create-data-connector', $instructions); + $this->assertStringContainsString('Prefer clear connector names', $instructions); + $this->assertStringContainsString('connector-naming', $instructions); + $this->assertStringNotContainsString('Name connectors by target system', $instructions); + $this->assertStringNotContainsString('screen-styles', $instructions); + $this->assertStringNotContainsString('process-naming', $instructions); + } + + public function testSkillResourcesAreDataConnectorScoped(): void + { + $this->seedMcpGuidance(); + + $server = app(DataConnectorsServer::class, ['transport' => new FakeTransporter()]); + $resources = $server->createContext()->resources(); + + $this->assertCount(1, $resources); + $this->assertInstanceOf(McpSkillResource::class, $resources->first()); + $this->assertSame('pm://mcp/skills/connector-naming', $resources->first()->uri()); + } + + public function testGetMcpGuidanceReturnsScopedCatalog(): void + { + $this->seedMcpGuidance(); + + DataConnectorsServer::actingAs($this->user) + ->tool(GetMcpGuidanceTool::class) + ->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('system_prompt', 'Prefer clear connector names') + ->has('skills', 1) + ->where('skills.0.slug', 'connector-naming') + ->missing('skills.0.content') + ->etc()); + } + + private function seedMcpGuidance(): void + { + Setting::updateOrCreate(['key' => McpGuidance::SYSTEM_PROMPT_KEY], [ + 'format' => 'textarea', + 'config' => 'Prefer clear connector names', + 'name' => 'System Prompt', + 'group' => 'MCP', + ]); + + Setting::updateOrCreate(['key' => McpGuidance::SKILLS_KEY], [ + 'format' => 'component', + 'config' => [ + [ + 'id' => 'custom-screen-styles', + 'name' => 'Screen styles', + 'slug' => 'screen-styles', + 'when' => 'Before create-screen when styling matters', + 'content' => 'Use calm colors', + 'scope' => McpGuidance::SCOPE_SCREENS, + ], + [ + 'id' => 'custom-process-naming', + 'name' => 'Process naming', + 'slug' => 'process-naming', + 'when' => 'Before create-process', + 'content' => 'Name processes by outcome', + 'scope' => McpGuidance::SCOPE_PROCESSES, + ], + [ + 'id' => 'custom-connector-naming', + 'name' => 'Connector naming', + 'slug' => 'connector-naming', + 'when' => 'Before create-data-connector', + 'content' => 'Name connectors by target system', + 'scope' => McpGuidance::SCOPE_DATA_CONNECTORS, + ], + ], + 'name' => 'Skills', + 'group' => 'MCP', + 'ui' => ['component' => 'McpSkills'], + ]); + } +} diff --git a/tests/Feature/Mcp/FlowGenieServerTest.php b/tests/Feature/Mcp/FlowGenieServerTest.php new file mode 100644 index 0000000000..0f2347683d --- /dev/null +++ b/tests/Feature/Mcp/FlowGenieServerTest.php @@ -0,0 +1,166 @@ +user = User::factory()->create([ + 'password' => Hash::make('password'), + 'is_administrator' => true, + ]); + + if (!class_exists(FlowGenie::class)) { + $this->markTestSkipped('package-ai is not installed'); + } + } + + public function testAdminCanCreateListUpdateAndDeleteAFlowGenie(): void + { + $category = FlowGenieCategory::query()->create([ + 'name' => 'MCP FlowGenie Category', + 'status' => 'ACTIVE', + 'is_system' => false, + ]); + + $created = FlowGenieServer::actingAs($this->user)->tool(CreateFlowGenieTool::class, [ + 'name' => 'MCP Review Assistant', + 'description' => 'Summarize requests and suggest approve or reject', + 'flow_genie_category_id' => (string) $category->id, + 'config' => [ + 'prompt' => 'Summarize the request data and suggest APPROVED or REJECTED.', + 'response_format' => 'json', + 'model' => 'gpt-4o-mini', + 'provider' => 'openai', + ], + ]); + + $created->assertOk() + ->assertHasNoErrors() + ->assertSee('MCP Review Assistant') + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('name', 'MCP Review Assistant') + ->where('has_instructions', true) + ->where('output_type', 'JSON') + ->where('config.instructions', 'Summarize the request data and suggest APPROVED or REJECTED.') + ->etc()); + + $genie = FlowGenie::query()->where('name', 'MCP Review Assistant')->firstOrFail(); + + FlowGenieServer::actingAs($this->user)->tool(ListFlowGeniesTool::class, [ + 'filter' => 'MCP Review', + ])->assertOk()->assertSee('MCP Review Assistant'); + + FlowGenieServer::actingAs($this->user)->tool(ListFlowGenieCategoriesTool::class, [ + 'filter' => 'MCP FlowGenie', + ])->assertOk()->assertSee('MCP FlowGenie Category'); + + FlowGenieServer::actingAs($this->user)->tool(GetFlowGenieTool::class, [ + 'id' => $genie->id, + ])->assertOk()->assertSee('gpt-4o-mini'); + + FlowGenieServer::actingAs($this->user)->tool(UpdateFlowGenieTool::class, [ + 'id' => $genie->id, + 'description' => 'Updated description for MCP FlowGenie', + 'config' => [ + 'instructions' => 'Return only a short JSON decision.', + 'output_type' => 'JSON', + 'model' => 'gpt-4o-mini', + 'provider' => 'openai', + ], + ])->assertOk() + ->assertSee('Updated description for MCP FlowGenie') + ->assertSee('Return only a short JSON decision.'); + + FlowGenieServer::actingAs($this->user)->tool(DeleteFlowGenieTool::class, [ + 'id' => $genie->id, + ])->assertOk()->assertSee('deleted'); + + $this->assertDatabaseMissing('flow_genies', ['id' => $genie->id]); + } + + public function testValidateFlowGenieReturnsNormalizedConfig(): void + { + FlowGenieServer::actingAs($this->user)->tool(ValidateFlowGenieTool::class, [ + 'config' => [ + 'prompt' => 'Hello agent', + 'response_format' => 'text', + ], + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('ok', true) + ->where('normalized.instructions', 'Hello agent') + ->where('normalized.output_type', 'Text (default)') + ->etc()); + } + + public function testGuidanceListsFlowGenieScopedCustomSkill(): void + { + Setting::updateOrCreate([ + 'key' => McpGuidance::SKILLS_KEY, + ], [ + 'format' => 'component', + 'config' => [ + [ + 'id' => 'custom-screen-styles', + 'name' => 'Screen styles', + 'slug' => 'screen-styles', + 'when' => 'Before create-screen when styling matters', + 'content' => 'Use calm colors', + 'scope' => McpGuidance::SCOPE_SCREENS, + ], + [ + 'id' => 'custom-genie-tone', + 'name' => 'Genie tone', + 'slug' => 'genie-tone', + 'when' => 'Before create-flow-genie', + 'content' => 'Keep a friendly tone', + 'scope' => McpGuidance::SCOPE_FLOW_GENIES, + ], + ], + 'name' => 'Skills', + 'group' => 'MCP', + ]); + + FlowGenieServer::actingAs($this->user)->tool(GetMcpGuidanceTool::class) + ->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->has('skills', 1) + ->where('skills.0.slug', 'genie-tone') + ->missing('skills.0.content') + ->etc()); + + $server = app(FlowGenieServer::class, ['transport' => new FakeTransporter()]); + $resources = $server->createContext()->resources(); + + $this->assertCount(1, $resources); + $this->assertInstanceOf(McpSkillResource::class, $resources->first()); + $this->assertSame('pm://mcp/skills/genie-tone', $resources->first()->uri()); + } +} diff --git a/tests/Feature/Mcp/McpOAuthTest.php b/tests/Feature/Mcp/McpOAuthTest.php new file mode 100644 index 0000000000..c79c2d1eed --- /dev/null +++ b/tests/Feature/Mcp/McpOAuthTest.php @@ -0,0 +1,85 @@ +getJson('/.well-known/oauth-protected-resource/mcp/processes') + ->assertOk() + ->assertJsonPath('scopes_supported.0', 'mcp:use') + ->assertJsonStructure([ + 'resource', + 'authorization_servers', + 'scopes_supported', + ]); + } + + public function testAuthorizationServerMetadataIncludesRegistration(): void + { + $this->getJson('/.well-known/oauth-authorization-server') + ->assertOk() + ->assertJsonPath('scopes_supported.0', 'mcp:use') + ->assertJsonStructure([ + 'issuer', + 'authorization_endpoint', + 'token_endpoint', + 'registration_endpoint', + 'code_challenge_methods_supported', + ]); + } + + public function testDynamicClientRegistrationCreatesPassportClient(): void + { + $response = $this->postJson('/oauth/register', [ + 'client_name' => 'Cursor MCP', + 'redirect_uris' => ['cursor://anysphere.cursor-mcp/oauth/callback'], + ]); + + $response->assertOk() + ->assertJsonPath('scope', 'mcp:use') + ->assertJsonPath('token_endpoint_auth_method', 'none') + ->assertJsonStructure([ + 'client_id', + 'grant_types', + 'redirect_uris', + ]); + + $this->assertNotNull(Client::query()->where('name', 'Cursor MCP')->first()); + } + + public function testMcpHttpUnauthorizedIncludesResourceMetadataHeader(): void + { + $response = $this->postJson('/mcp/processes', [ + 'jsonrpc' => '2.0', + 'id' => 1, + 'method' => 'initialize', + 'params' => [], + ]); + + $response->assertUnauthorized(); + + $wwwAuthenticate = (string) $response->headers->get('WWW-Authenticate'); + $this->assertStringContainsString('Bearer realm="mcp"', $wwwAuthenticate); + $this->assertStringContainsString('resource_metadata=', $wwwAuthenticate); + } + + public function testMcpGetProbeReturnsUnauthorizedWithResourceMetadata(): void + { + $response = $this->getJson('/mcp/processes'); + + $response->assertUnauthorized() + ->assertJsonPath('error', 'Unauthorized'); + + $wwwAuthenticate = (string) $response->headers->get('WWW-Authenticate'); + $this->assertStringContainsString('Bearer realm="mcp"', $wwwAuthenticate); + $this->assertStringContainsString('oauth-protected-resource/mcp/processes', $wwwAuthenticate); + } +} + diff --git a/tests/Feature/Mcp/McpSettingsSeederTest.php b/tests/Feature/Mcp/McpSettingsSeederTest.php new file mode 100644 index 0000000000..2fdedaa961 --- /dev/null +++ b/tests/Feature/Mcp/McpSettingsSeederTest.php @@ -0,0 +1,69 @@ + SettingsMenus::INTEGRATIONS_MENU_GROUP, + ], [ + 'menu_group_order' => 2, + 'ui' => json_encode(['icon' => 'puzzle-piece']), + ]); + } + + public function testSeederCreatesEmptySettingsWithoutBuiltInSkills(): void + { + $this->createIntegrationsMenu(); + + $this->seed(McpSettingsSeeder::class); + + $this->assertSame([], Setting::configByKey(McpGuidance::SKILLS_KEY)); + $this->assertNotNull(Setting::where('key', McpGuidance::SYSTEM_PROMPT_KEY)->first()); + } + + public function testSeederKeepsExistingCustomSkillsAndSystemPrompt(): void + { + $this->createIntegrationsMenu(); + + Setting::factory()->create([ + 'key' => McpGuidance::SYSTEM_PROMPT_KEY, + 'format' => 'textarea', + 'config' => 'Always be brief', + 'name' => 'System Prompt', + 'group' => 'MCP', + ]); + Setting::factory()->create([ + 'key' => McpGuidance::SKILLS_KEY, + 'format' => 'component', + 'config' => [ + [ + 'id' => 'custom-1', + 'name' => 'Japanese labels', + 'slug' => 'japanese-labels', + 'when' => 'Before create-screen', + 'content' => 'Always use Japanese labels', + ], + ], + 'name' => 'Skills', + 'group' => 'MCP', + 'ui' => ['component' => 'McpSkills'], + ]); + + $this->seed(McpSettingsSeeder::class); + $this->seed(McpSettingsSeeder::class); + + $skills = Setting::configByKey(McpGuidance::SKILLS_KEY); + $this->assertCount(1, $skills); + $this->assertSame('custom-1', $skills[0]['id']); + $this->assertSame('Always be brief', Setting::configByKey(McpGuidance::SYSTEM_PROMPT_KEY)); + } +} diff --git a/tests/Feature/Mcp/ProcessServerTest.php b/tests/Feature/Mcp/ProcessServerTest.php new file mode 100644 index 0000000000..0bf88155e0 --- /dev/null +++ b/tests/Feature/Mcp/ProcessServerTest.php @@ -0,0 +1,765 @@ +create(); + $bpmn = Process::getProcessTemplate('OnlyStartElement.bpmn'); + + $created = ProcessServer::actingAs($this->user)->tool(CreateProcessTool::class, [ + 'name' => 'MCP Intake Flow', + 'description' => 'Created via MCP', + 'process_category_id' => (string) $category->id, + 'bpmn' => $bpmn, + ]); + + $created->assertOk() + ->assertHasNoErrors() + ->assertSee('MCP Intake Flow') + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('name', 'MCP Intake Flow') + ->where('description', 'Created via MCP') + ->whereType('bpmn', 'string') + ->etc()); + + $process = Process::where('name', 'MCP Intake Flow')->firstOrFail(); + Event::assertDispatched(ProcessCreated::class); + + ProcessServer::actingAs($this->user)->tool(ListProcessesTool::class, [ + 'filter' => 'MCP Intake', + ])->assertOk()->assertSee('MCP Intake Flow'); + + ProcessServer::actingAs($this->user)->tool(GetProcessTool::class, [ + 'id' => $process->id, + ])->assertOk()->assertSee('Created via MCP'); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'description' => 'Updated via MCP', + ])->assertOk()->assertSee('Updated via MCP'); + + $this->assertSame('Updated via MCP', $process->refresh()->description); + } + + public function testProcessToolsRequireAnAuthenticatedUserWithPermission(): void + { + ProcessServer::tool(ListProcessesTool::class) + ->assertHasErrors(['Authenticate with a ProcessMaker API token']); + + $member = User::factory()->create([ + 'is_administrator' => false, + ]); + + ProcessServer::actingAs($member)->tool(ListProcessesTool::class) + ->assertHasErrors(['view-processes']); + } + + public function testPlanProcessReturnsOpenQuestionsThenBlueprint(): void + { + ProcessServer::actingAs($this->user)->tool(PlanProcessTool::class, [ + 'goal' => 'Employee leave request with manager approval', + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('ready', false) + ->whereType('open_questions', 'array') + ->where('open_questions.0.id', 'name') + ->etc()); + + ProcessServer::actingAs($this->user)->tool(PlanProcessTool::class, [ + 'goal' => 'Employee leave request with manager approval', + 'name' => 'Leave Request', + 'purpose' => 'Employees request PTO; managers approve or reject.', + 'tasks' => '1) Submit request (form) 2) Manager review (form)', + 'decisions' => 'After review: Approved vs Rejected on approval_status', + 'assignments' => 'Submit=requester; Review=process_manager', + 'process_manager' => 'admin', + 'screens' => 'Create FORM submit + FORM approval + DISPLAY summary', + 'start' => 'Requester from Requests UI with interstitial', + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('ready', true) + ->where('blueprint.name', 'Leave Request') + ->whereType('blueprint.next_steps', 'array') + ->etc()); + } + + public function testListUsersAndGroupsForAssignment(): void + { + $peer = User::factory()->create([ + 'username' => 'pto.manager', + 'firstname' => 'Pto', + 'lastname' => 'Manager', + 'status' => 'ACTIVE', + 'is_administrator' => false, + ]); + $group = Group::factory()->create([ + 'name' => 'PTO Approvers', + 'status' => 'ACTIVE', + ]); + + ProcessServer::actingAs($this->user)->tool(ListUsersTool::class, [ + 'filter' => 'pto.manager', + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('data.0.id', $peer->id) + ->where('data.0.username', 'pto.manager') + ->etc()); + + ProcessServer::actingAs($this->user)->tool(ListGroupsTool::class, [ + 'filter' => 'PTO Approvers', + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('data.0.id', $group->id) + ->where('data.0.name', 'PTO Approvers') + ->etc()); + } + + public function testListGroupsFindsExactNameAndReportsMembersAndDuplicates(): void + { + $group = Group::factory()->create(['name' => 'Requesters Exact', 'status' => 'ACTIVE']); + Group::factory()->create(['name' => 'Requesters Exact Plus', 'status' => 'ACTIVE']); + $group->groupMembers()->create([ + 'member_id' => $this->user->id, + 'member_type' => User::class, + ]); + + ProcessServer::actingAs($this->user)->tool(ListGroupsTool::class, [ + 'filter' => 'Requesters Exact', + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->has('data', 2) + ->etc()); + + ProcessServer::actingAs($this->user)->tool(ListGroupsTool::class, [ + 'name' => 'requesters exact', + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->has('data', 1) + ->where('data.0.id', $group->id) + ->where('data.0.members_count', 1) + ->where('data.0.same_name_count', 1) + ->etc()); + } + + public function testCreateGroupCreatesAnActiveGroupAndRejectsDuplicates(): void + { + ProcessServer::actingAs($this->user)->tool(CreateGroupTool::class, [ + 'name' => 'Deal Closing Legal', + 'description' => 'Legal sign-off', + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('name', 'Deal Closing Legal') + ->where('status', 'ACTIVE') + ->where('members_count', 0) + ->etc()); + + $this->assertSame(1, Group::where('name', 'Deal Closing Legal')->count()); + + ProcessServer::actingAs($this->user)->tool(CreateGroupTool::class, [ + 'name' => 'Deal Closing Legal', + ])->assertHasErrors(['has already been taken']); + + ProcessServer::actingAs($this->user)->tool(CreateGroupTool::class, [ + 'name' => 'Bad_Name!', + ])->assertHasErrors(['may only contain alphanumeric characters']); + } + + public function testCreateGroupEnforcesTheTwoFactorPolicy(): void + { + config(['password-policies.2fa_enabled' => true]); + ProcessServer::actingAs($this->user)->tool(CreateGroupTool::class, [ + 'name' => 'TwoFactorOnGroup', + 'enabled_2fa' => false, + ])->assertOk(); + $this->assertTrue((bool) Group::where('name', 'TwoFactorOnGroup')->value('enabled_2fa')); + + config(['password-policies.2fa_enabled' => false]); + ProcessServer::actingAs($this->user)->tool(CreateGroupTool::class, [ + 'name' => 'TwoFactorOffGroup', + 'enabled_2fa' => true, + ])->assertOk(); + $this->assertFalse((bool) Group::where('name', 'TwoFactorOffGroup')->value('enabled_2fa')); + } + + public function testCreateGroupRequiresThePermission(): void + { + $this->initializePermissions(); + $member = User::factory()->create(['is_administrator' => false]); + $member->permissions()->attach(Permission::byName('create-processes')); + + ProcessServer::actingAs($member)->tool(CreateGroupTool::class, [ + 'name' => 'Not Allowed Group', + ])->assertHasErrors(['create-groups']); + + $this->assertSame(0, Group::where('name', 'Not Allowed Group')->count()); + } + + public function testProcessInventoryMapsAssetsFieldsAndGatewayVariables(): void + { + $screen = Screen::factory()->create([ + 'title' => 'Inventory Form', + 'type' => 'FORM', + 'config' => [[ + 'name' => 'Page', + 'items' => [ + ['component' => 'FormInput', 'config' => ['name' => 'DC_FLAG']], + ['component' => 'FormButton', 'config' => ['name' => 'submit']], + ['component' => 'FormMultiColumn', 'config' => [], 'items' => [ + [['component' => 'FormTextArea', 'config' => ['name' => 'DC_NOTES']]], + [], + ]], + ], + ]], + ]); + $script = Script::factory()->create(['title' => 'Inventory Script', 'language' => 'php']); + + $bpmn = $this->inventoryBpmn($screen->id, $script->id); + $process = Process::factory()->create(['name' => 'Inventory Process', 'bpmn' => $bpmn]); + + ProcessServer::actingAs($this->user)->tool(GetProcessInventoryTool::class, [ + 'id' => $process->id, + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('process.id', $process->id) + ->where('counts.activities', 2) + ->where('counts.gateways', 1) + ->where('counts.sequence_flows', 3) + ->where('screens.0.title', 'Inventory Form') + ->where('screens.0.controls', 4) + ->where('screens.0.fields', ['DC_FLAG', 'DC_NOTES']) + ->where('scripts.0.title', 'Inventory Script') + ->where('activities.0.screen_title', 'Inventory Form') + ->where('activities.1.script_title', 'Inventory Script') + ->where('gateways.0.variables', ['DC_FLAG', 'DC_MISSING']) + ->where('variables.DC_FLAG.written_by_screens', [$screen->id]) + ->where('variables.DC_MISSING.written_by_screens', []) + ->where('variables.DC_MISSING.read_by_gateways', ['gate_1']) + ->has('warnings', 1) + ->etc()); + } + + public function testUpdateProcessStripsMarkupFromCaseTitleAndKeepsMustache(): void + { + $process = Process::factory()->create(['name' => 'Case Title Process']); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'case_title' => 'Case #{{_request.case_number}}', + ])->assertOk(); + + $this->assertSame('Case #{{_request.case_number}}', $process->refresh()->case_title); + } + + public function testInventoryHidesScriptsWithoutViewScriptsPermission(): void + { + $this->initializePermissions(); + $screen = Screen::factory()->create(['title' => 'Inventory Form', 'type' => 'FORM', 'config' => []]); + $script = Script::factory()->create(['title' => 'Hidden Script', 'language' => 'php']); + $process = Process::factory()->create([ + 'name' => 'Inventory Process', + 'bpmn' => $this->inventoryBpmn($screen->id, $script->id), + ]); + $member = User::factory()->create(['is_administrator' => false]); + $member->permissions()->attach(Permission::byName('view-processes')); + + ProcessServer::actingAs($member)->tool(GetProcessInventoryTool::class, [ + 'id' => $process->id, + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('scripts', []) + ->etc()) + ->assertDontSee('Hidden Script'); + } + + private function inventoryBpmn(int $screenId, int $scriptId): string + { + return << + + + flow_1 + + flow_1flow_2 + + + flow_2flow_3 + + + flow_3 + + + + + DC_FLAG == 'YES' && DC_MISSING != '' + + + +XML; + } + + public function testValidateProcessReportsMissingScreenRef(): void + { + $bpmn = <<<'XML' + + + + + node_4 + + + node_4 + node_5 + + + node_5 + + + + + + + + +XML; + + ProcessServer::actingAs($this->user)->tool(ValidateProcessTool::class, [ + 'bpmn' => $bpmn, + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('ok', false) + ->where('errors.0.code', 'missing_screen_ref') + ->etc()); + } + + public function testHttpServerRequiresABearerToken(): void + { + $this->postJson('/mcp/processes', [ + 'jsonrpc' => '2.0', + 'id' => 1, + 'method' => 'initialize', + 'params' => [], + ])->assertUnauthorized(); + } + + public function testGetMcpGuidanceReturnsProcessScopedCatalog(): void + { + $this->seedMcpGuidance(); + + ProcessServer::actingAs($this->user) + ->tool(GetMcpGuidanceTool::class) + ->assertOk() + ->assertHasNoErrors() + ->assertSee([ + 'Prefer clear process names', + 'Process naming', + ]) + ->assertDontSee('screen-styles') + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('system_prompt', 'Prefer clear process names') + ->where('skills.0.slug', 'process-naming') + ->missing('skills.0.content') + ->etc()); + } + + public function testGetMcpSkillReturnsFullSkillBodyBySlug(): void + { + $this->seedMcpGuidance(); + + ProcessServer::actingAs($this->user) + ->tool(GetMcpSkillTool::class, ['slug' => 'process-naming']) + ->assertOk() + ->assertHasNoErrors() + ->assertSee('Name processes by outcome') + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('slug', 'process-naming') + ->where('content', 'Name processes by outcome') + ->where('uri', 'pm://mcp/skills/process-naming') + ->etc()); + } + + public function testServerInstructionsIncludeProcessCatalogWithoutSkillBodies(): void + { + $this->seedMcpGuidance(); + + $server = app(ProcessServer::class, ['transport' => new FakeTransporter()]); + $instructions = $server->createContext()->instructions; + + $this->assertStringContainsString('get-mcp-guidance', $instructions); + $this->assertStringContainsString('validate-process', $instructions); + $this->assertStringContainsString('Prefer clear process names', $instructions); + $this->assertStringContainsString('process-naming', $instructions); + $this->assertStringNotContainsString('Name processes by outcome', $instructions); + $this->assertStringNotContainsString('screen-styles', $instructions); + } + + public function testSkillResourcesAreProcessScoped(): void + { + $this->seedMcpGuidance(); + + $server = app(ProcessServer::class, ['transport' => new FakeTransporter()]); + $resources = $server->createContext()->resources(); + + $this->assertCount(1, $resources); + $this->assertInstanceOf(McpSkillResource::class, $resources->first()); + $this->assertSame('pm://mcp/skills/process-naming', $resources->first()->uri()); + } + + public function testMetadataUpdateDoesNotPublishDraftBpmn(): void + { + $publishedBpmn = Process::getProcessTemplate('OnlyStartElement.bpmn'); + $process = Process::factory()->create([ + 'name' => 'Published Definition', + 'description' => 'Live', + 'bpmn' => $publishedBpmn, + ]); + + $draftBpmn = str_replace('name="ProcessName"', 'name="UnpublishedDraft"', $publishedBpmn); + $process->bpmn = $draftBpmn; + $process->saveDraft('A'); + $process->refresh(); + + $this->assertSame($publishedBpmn, $process->bpmn); + $this->assertNotNull($process->getDraftVersion('A')); + $this->assertStringContainsString('UnpublishedDraft', (string) $process->getDraftVersion('A')->bpmn); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'name' => 'Renamed Without Publish', + 'description' => 'Metadata only', + ])->assertOk()->assertSee('Renamed Without Publish'); + + $process->refresh(); + $this->assertSame('Renamed Without Publish', $process->name); + $this->assertSame('Metadata only', $process->description); + $this->assertSame($this->user->id, (int) $process->updated_by); + // Must keep the published definition; must not hydrate draft BPMN onto live. + $this->assertSame($publishedBpmn, $process->bpmn); + $this->assertStringNotContainsString('UnpublishedDraft', (string) $process->bpmn); + // Metadata-only save must not delete unpublished drafts via HasVersioning. + $draft = $process->getDraftVersion('A'); + $this->assertNotNull($draft); + $this->assertStringContainsString('UnpublishedDraft', (string) $draft->bpmn); + } + + public function testUpdateProcessSavesCaseTitleManagersAndNotificationsWithoutPublishing(): void + { + $publishedBpmn = Process::getProcessTemplate('OnlyStartElement.bpmn'); + $process = Process::factory()->create(['name' => 'Settings Process', 'bpmn' => $publishedBpmn]); + $manager = User::factory()->create(); + $versionsBefore = ProcessVersion::where('process_id', $process->id)->count(); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'case_title' => '{{customer}} request', + 'manager_id' => [$manager->id], + 'notifications' => ['requester' => ['started' => true, 'error' => true]], + ])->assertOk() + ->assertHasNoErrors() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('case_title', '{{customer}} request') + ->where('manager_id', [$manager->id]) + ->where('notifications.requester.started', true) + ->where('notifications.requester.completed', false) + ->etc()); + + $process->refresh(); + $this->assertSame('{{customer}} request', $process->case_title); + $this->assertSame([$manager->id], array_map('intval', $process->manager_id)); + $this->assertTrue($process->notifications->requester['started']); + $this->assertTrue($process->notifications->requester['error']); + $this->assertFalse($process->notifications->assignee['started']); + $this->assertSame($publishedBpmn, $process->bpmn); + $this->assertSame($versionsBefore, ProcessVersion::where('process_id', $process->id)->count()); + $this->assertSame($this->user->id, (int) $process->updated_by); + } + + public function testNotificationUpdateOnlyChangesTheSentPairs(): void + { + $process = Process::factory()->create([ + 'name' => 'Notification Pairs', + 'bpmn' => Process::getProcessTemplate('OnlyStartElement.bpmn'), + ]); + $tool = fn (array $notifications) => ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'notifications' => $notifications, + ]); + + $tool(['requester' => ['started' => true], 'assignee' => ['completed' => true]])->assertOk(); + $tool(['requester' => ['started' => false], 'manager' => ['error' => true]])->assertOk(); + + $notifications = $process->refresh()->notifications; + $this->assertFalse($notifications->requester['started']); + $this->assertTrue($notifications->assignee['completed']); + $this->assertTrue($notifications->manager['error']); + } + + public function testUpdateProcessRejectsUnknownNotificationKeysAndManagers(): void + { + $process = Process::factory()->create([ + 'name' => 'Rejected Settings', + 'bpmn' => Process::getProcessTemplate('OnlyStartElement.bpmn'), + ]); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'notifications' => ['requestr' => ['started' => true]], + ])->assertHasErrors(['Unknown notifiable type "requestr"']); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'notifications' => ['requester' => ['finished' => true]], + ])->assertHasErrors(['Unknown notification type "finished"']); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'manager_id' => [99999999], + ])->assertHasErrors(['The selected Manager_id.0 is invalid.']); + + $this->assertSame(0, $process->refresh()->notification_settings()->count()); + } + + public function testUpdateProcessClearsManagersWithAnEmptyArray(): void + { + $manager = User::factory()->create(); + $process = Process::factory()->create([ + 'name' => 'Clear Managers', + 'bpmn' => Process::getProcessTemplate('OnlyStartElement.bpmn'), + ]); + $process->manager_id = [$manager->id]; + $process->saveOrFail(); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'manager_id' => [], + ])->assertOk()->assertHasNoErrors(); + + $this->assertSame([], $process->refresh()->manager_id); + } + + public function testCombinedBpmnAndMetadataUpdatePersistsLiveMetadata(): void + { + $publishedBpmn = Process::getProcessTemplate('OnlyStartElement.bpmn'); + $oldCategory = ProcessCategory::factory()->create(); + $newCategory = ProcessCategory::factory()->create(); + $process = Process::factory()->create([ + 'name' => 'Before Combined Update', + 'description' => 'Old description', + 'status' => 'ACTIVE', + 'process_category_id' => (string) $oldCategory->id, + 'bpmn' => $publishedBpmn, + ]); + + $draftBpmn = str_replace('name="ProcessName"', 'name="CombinedDraft"', $publishedBpmn); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'name' => 'After Combined Update', + 'description' => 'New description', + 'status' => 'INACTIVE', + 'process_category_id' => (string) $newCategory->id, + 'bpmn' => $draftBpmn, + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('name', 'After Combined Update') + ->where('description', 'New description') + ->where('status', 'INACTIVE') + ->etc()); + + $process->refresh(); + $this->assertSame('After Combined Update', $process->name); + $this->assertSame('New description', $process->description); + $this->assertSame('INACTIVE', $process->status); + $this->assertSame((string) $newCategory->id, (string) $process->process_category_id); + $this->assertTrue($process->categories()->where('category_id', $newCategory->id)->exists()); + // Draft BPMN is saved; published process row keeps the prior definition. + $this->assertSame($publishedBpmn, $process->bpmn); + $draft = $process->getDraftVersion('A'); + $this->assertNotNull($draft); + $this->assertStringContainsString('CombinedDraft', (string) $draft->bpmn); + } + + public function testGetProcessHidesDraftBpmnWithoutEditPermission(): void + { + $publishedBpmn = Process::getProcessTemplate('OnlyStartElement.bpmn'); + $process = Process::factory()->create([ + 'name' => 'Secret Draft Process', + 'bpmn' => $publishedBpmn, + ]); + + $draftBpmn = str_replace('name="ProcessName"', 'name="UnpublishedSecret"', $publishedBpmn); + $process->bpmn = $draftBpmn; + $process->saveDraft('A'); + $process->refresh(); + + $this->initializePermissions(); + $viewer = User::factory()->create(['is_administrator' => false]); + $viewer->permissions()->attach(Permission::byName('view-processes')); + + ProcessServer::actingAs($viewer)->tool(GetProcessTool::class, [ + 'id' => $process->id, + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('name', 'Secret Draft Process') + ->where('alternative', 'A') + ->where('bpmn', $publishedBpmn) + ->etc()); + + // Requesting B must not return live A XML labeled as B. + ProcessServer::actingAs($viewer)->tool(GetProcessTool::class, [ + 'id' => $process->id, + 'alternative' => 'B', + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('alternative', 'A') + ->where('bpmn', $publishedBpmn) + ->etc()); + + // Invalid draft: view-only validates published; editor validates draft. + $process->bpmn = ''; + $process->saveDraft('A'); + + ProcessServer::actingAs($viewer)->tool(ValidateProcessTool::class, [ + 'id' => $process->id, + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('ok', true) + ->etc()); + + ProcessServer::actingAs($this->user)->tool(ValidateProcessTool::class, [ + 'id' => $process->id, + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('ok', false) + ->etc()); + + ProcessServer::actingAs($this->user)->tool(GetProcessTool::class, [ + 'id' => $process->id, + ])->assertOk()->assertSee('not-valid-bpmn'); + } + + public function testEnableProcessAlternativeBAndUpdateDraftOnB(): void + { + if (!class_exists(\ProcessMaker\Package\PackageABTesting\Models\Alternative::class)) { + $this->markTestSkipped('package-ab-testing is not installed.'); + } + + $bpmnA = Process::getProcessTemplate('OnlyStartElement.bpmn'); + $process = Process::factory()->create(['bpmn' => $bpmnA]); + + ProcessServer::actingAs($this->user)->tool(EnableProcessAlternativeBTool::class, [ + 'id' => $process->id, + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('b_enabled', true) + ->where('package_installed', true) + ->etc()); + + $bpmnB = str_replace('name="ProcessName"', 'name="ProcessNameB"', $bpmnA); + + ProcessServer::actingAs($this->user)->tool(UpdateProcessTool::class, [ + 'id' => $process->id, + 'alternative' => 'B', + 'bpmn' => $bpmnB, + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('alternative', 'B') + ->etc()); + + $draftB = $process->refresh()->getDraftVersion('B'); + $this->assertNotNull($draftB); + $this->assertStringContainsString('ProcessNameB', (string) $draftB->bpmn); + + $draftA = $process->getDraftVersion('A'); + $bpmnDraftA = $draftA ? $draftA->bpmn : $process->getLatestVersion('A')->bpmn; + $this->assertStringNotContainsString('ProcessNameB', (string) $bpmnDraftA); + + ProcessServer::actingAs($this->user)->tool(GetProcessTool::class, [ + 'id' => $process->id, + 'alternative' => 'B', + ])->assertOk()->assertSee('ProcessNameB'); + } + + private function seedMcpGuidance(): void + { + Setting::factory()->create([ + 'key' => McpGuidance::SYSTEM_PROMPT_KEY, + 'format' => 'textarea', + 'config' => 'Prefer clear process names', + 'name' => 'System Prompt', + 'group' => 'MCP', + ]); + + Setting::factory()->create([ + 'key' => McpGuidance::SKILLS_KEY, + 'format' => 'component', + 'config' => [ + [ + 'id' => 'custom-screen-styles', + 'name' => 'Screen styles', + 'slug' => 'screen-styles', + 'when' => 'Before create-screen when styling matters', + 'content' => 'Use calm colors', + 'scope' => McpGuidance::SCOPE_SCREENS, + ], + [ + 'id' => 'custom-process-naming', + 'name' => 'Process naming', + 'slug' => 'process-naming', + 'when' => 'Before create-process', + 'content' => 'Name processes by outcome', + 'scope' => McpGuidance::SCOPE_PROCESSES, + ], + ], + 'name' => 'Skills', + 'group' => 'MCP', + 'ui' => ['component' => 'McpSkills'], + ]); + } +} diff --git a/tests/Feature/Mcp/ScreenServerTest.php b/tests/Feature/Mcp/ScreenServerTest.php new file mode 100644 index 0000000000..7e0c5d591d --- /dev/null +++ b/tests/Feature/Mcp/ScreenServerTest.php @@ -0,0 +1,381 @@ +create(); + $created = ScreenServer::actingAs($this->user)->tool(CreateScreenTool::class, [ + 'title' => 'Intake Form', + 'description' => 'Collects intake details', + 'type' => 'FORM', + 'screen_category_id' => $category->id, + 'config' => [ + ['name' => 'Intake'], + ], + ]); + + $created->assertOk() + ->assertHasNoErrors() + ->assertSee('Intake Form') + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('title', 'Intake Form') + ->where('type', 'FORM') + ->where('config.0.name', 'Intake') + ->etc()); + + $screen = Screen::where('title', 'Intake Form')->firstOrFail(); + Event::assertDispatched(ScreenCreated::class); + + ScreenServer::actingAs($this->user)->tool(ListScreensTool::class, [ + 'filter' => 'Intake', + ])->assertOk()->assertSee('Intake Form'); + + ScreenServer::actingAs($this->user)->tool(GetScreenTool::class, [ + 'id' => $screen->id, + ])->assertOk()->assertSee('Collects intake details'); + + ScreenServer::actingAs($this->user)->tool(UpdateScreenTool::class, [ + 'id' => $screen->id, + 'description' => 'Updated intake details', + ])->assertOk()->assertSee('Updated intake details'); + + $this->assertSame('Updated intake details', $screen->refresh()->description); + Event::assertDispatched(ScreenUpdated::class); + + ScreenServer::actingAs($this->user)->tool(DeleteScreenTool::class, [ + 'id' => $screen->id, + ])->assertOk()->assertStructuredContent([ + 'id' => $screen->id, + 'deleted' => true, + ]); + + $this->assertNull(Screen::find($screen->id)); + Event::assertDispatched(ScreenDeleted::class); + } + + public function testScreenToolsRequireAnAuthenticatedUserWithPermission(): void + { + ScreenServer::tool(ListScreensTool::class) + ->assertHasErrors(['Authenticate with a ProcessMaker API token']); + + $member = User::factory()->create([ + 'is_administrator' => false, + ]); + + ScreenServer::actingAs($member)->tool(ListScreensTool::class) + ->assertHasErrors(['view-screens']); + } + + public function testDefaultScreensCannotBeDeleted(): void + { + $screen = Screen::factory()->create([ + 'is_default' => 1, + ]); + + ScreenServer::actingAs($this->user)->tool(DeleteScreenTool::class, [ + 'id' => $screen->id, + ])->assertHasErrors(['Default screens cannot be deleted.']); + + $this->assertNotNull(Screen::find($screen->id)); + } + + public function testCreateScreenNormalizesMissingInspectorAndItems(): void + { + Event::fake([ScreenCreated::class]); + + $category = ScreenCategory::factory()->create(); + ScreenServer::actingAs($this->user)->tool(CreateScreenTool::class, [ + 'title' => 'MCP Safe Config', + 'description' => 'Ensures inspector defaults', + 'type' => 'FORM', + 'screen_category_id' => $category->id, + 'config' => [ + [ + 'name' => 'Page 1', + 'items' => [ + [ + 'component' => 'FormInput', + 'label' => 'Name', + 'config' => ['name' => 'name', 'label' => 'Name'], + ], + ], + ], + ], + 'computed' => null, + 'watchers' => null, + ])->assertOk()->assertHasNoErrors(); + + $screen = Screen::where('title', 'MCP Safe Config')->firstOrFail(); + $this->assertSame([], $screen->config[0]['items'][0]['inspector']); + $this->assertSame([], $screen->computed); + $this->assertSame([], $screen->watchers); + } + + public function testCreateScreenRejectsSelectListWithoutOptionsList(): void + { + $category = ScreenCategory::factory()->create(); + + ScreenServer::actingAs($this->user)->tool(CreateScreenTool::class, [ + 'title' => 'Broken Select Screen', + 'description' => 'Select missing optionsList', + 'type' => 'FORM', + 'screen_category_id' => $category->id, + 'config' => [ + [ + 'name' => 'Page 1', + 'items' => [ + [ + 'component' => 'FormSelectList', + 'inspector' => [], + 'config' => [ + 'name' => 'category', + 'label' => 'Category', + 'validation' => 'required', + 'options' => [ + 'dataSource' => 'provideData', + 'jsonData' => '[{"value":"Travel","content":"Travel"}]', + ], + ], + ], + ], + ], + ], + ])->assertHasErrors(['optionsList']); + } + + public function testNativeFormNoticeDependsOnSizeAndOnEditingANativeScreen(): void + { + ScreenServer::actingAs($this->user)->tool(ValidateScreenTool::class, [ + 'type' => 'FORM', + 'config' => $this->nativeConfig(2), + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('ok', true) + ->where('warnings', []) + ->where('info.0.code', 'native_small_screen') + ->etc()); + + ScreenServer::actingAs($this->user)->tool(ValidateScreenTool::class, [ + 'type' => 'FORM', + 'config' => $this->nativeConfig(6), + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('warnings.0.code', 'prefer_vue_component_editor') + ->where('info', []) + ->etc()); + + $stored = Screen::factory()->create(['type' => 'FORM', 'config' => $this->nativeConfig(8)]); + ScreenServer::actingAs($this->user)->tool(ValidateScreenTool::class, [ + 'id' => $stored->id, + 'config' => $this->nativeConfig(9), + ])->assertOk() + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('warnings', []) + ->where('info.0.code', 'native_screen_edit') + ->etc()); + } + + /** + * @return list> + */ + private function nativeConfig(int $inputs): array + { + $items = []; + for ($index = 0; $index < $inputs; $index++) { + $items[] = ['component' => 'FormInput', 'inspector' => [], 'config' => ['name' => 'field_' . $index]]; + } + + return [['name' => 'Page 1', 'items' => $items]]; + } + + public function testValidateScreenReportsSelectAndVueIssues(): void + { + ScreenServer::actingAs($this->user)->tool(ValidateScreenTool::class, [ + 'type' => 'FORM', + 'config' => [ + [ + 'name' => 'Page 1', + 'items' => [ + [ + 'component' => 'FormSelectList', + 'inspector' => [], + 'config' => [ + 'name' => 'category', + 'options' => [ + 'dataSource' => 'provideData', + ], + ], + ], + [ + 'component' => 'VueComponentRenderTemplate', + 'inspector' => [], + 'config' => [ + 'contentVue' => '', + 'components' => [], + ], + ], + ], + ], + ], + ])->assertOk()->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('ok', false) + ->has('errors') + ->etc()); + } + + public function testHttpServerRequiresABearerToken(): void + { + $this->postJson('/mcp/screens', [ + 'jsonrpc' => '2.0', + 'id' => 1, + 'method' => 'initialize', + 'params' => [], + ])->assertUnauthorized(); + } + + public function testGetMcpGuidanceReturnsCatalogWithoutSkillBodies(): void + { + $this->seedMcpGuidance(); + + ScreenServer::actingAs($this->user) + ->tool(GetMcpGuidanceTool::class) + ->assertOk() + ->assertHasNoErrors() + ->assertSee([ + 'Always use FormInput for customer names', + 'Screen Styles', + 'Before create-screen when styling matters', + ]) + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('system_prompt', 'Always use FormInput for customer names') + ->where('skills.0.name', 'Screen Styles') + ->where('skills.0.slug', 'screen-styles') + ->where('skills.0.when', 'Before create-screen when styling matters') + ->where('skills.0.uri', 'pm://mcp/skills/screen-styles') + ->missing('skills.0.content') + ->etc()); + } + + public function testGetMcpSkillReturnsFullSkillBodyBySlug(): void + { + $this->seedMcpGuidance(); + + ScreenServer::actingAs($this->user) + ->tool(GetMcpSkillTool::class, ['slug' => 'screen-styles']) + ->assertOk() + ->assertHasNoErrors() + ->assertSee('Prefer primary buttons') + ->assertStructuredContent(fn (AssertableJson $json) => $json + ->where('slug', 'screen-styles') + ->where('when', 'Before create-screen when styling matters') + ->where('content', 'Prefer primary buttons') + ->where('uri', 'pm://mcp/skills/screen-styles') + ->etc()); + + ScreenServer::actingAs($this->user) + ->tool(GetMcpSkillTool::class, ['slug' => 'missing-skill']) + ->assertHasErrors(['Skill not found for slug: missing-skill']); + } + + public function testServerInstructionsIncludeCatalogWithoutSkillBodies(): void + { + $this->seedMcpGuidance(); + + $server = app(ScreenServer::class, ['transport' => new FakeTransporter()]); + $instructions = $server->createContext()->instructions; + + $this->assertStringContainsString('get-mcp-guidance', $instructions); + $this->assertStringContainsString('get-mcp-skill', $instructions); + $this->assertStringContainsString('Always use FormInput for customer names', $instructions); + $this->assertStringContainsString('Skills catalog', $instructions); + $this->assertStringContainsString('Screen Styles', $instructions); + $this->assertStringContainsString('Before create-screen when styling matters', $instructions); + $this->assertStringContainsString('pm://mcp/skills/screen-styles', $instructions); + $this->assertStringNotContainsString('Prefer primary buttons', $instructions); + } + + public function testSkillResourcesAreRegisteredFromSettings(): void + { + $this->seedMcpGuidance(); + + $server = app(ScreenServer::class, ['transport' => new FakeTransporter()]); + $resources = $server->createContext()->resources(); + + $this->assertCount(1, $resources); + $this->assertInstanceOf(McpSkillResource::class, $resources->first()); + $this->assertSame('pm://mcp/skills/screen-styles', $resources->first()->uri()); + + ScreenServer::actingAs($this->user) + ->resource(new McpSkillResource( + 'Screen Styles', + 'screen-styles', + 'Prefer primary buttons', + 'Before create-screen when styling matters', + )) + ->assertOk() + ->assertSee('Prefer primary buttons'); + } + + private function seedMcpGuidance(): void + { + Setting::factory()->create([ + 'key' => McpGuidance::SYSTEM_PROMPT_KEY, + 'format' => 'textarea', + 'config' => 'Always use FormInput for customer names', + 'name' => 'System Prompt', + 'group' => 'MCP', + ]); + + Setting::factory()->create([ + 'key' => McpGuidance::SKILLS_KEY, + 'format' => 'component', + 'config' => [ + [ + 'id' => 'skill-1', + 'name' => 'Screen Styles', + 'slug' => 'screen-styles', + 'when' => 'Before create-screen when styling matters', + 'content' => 'Prefer primary buttons', + ], + ], + 'name' => 'Skills', + 'group' => 'MCP', + 'ui' => ['component' => 'McpSkills'], + ]); + } +} diff --git a/tests/Feature/ScheduledTaskDuplicationTest.php b/tests/Feature/ScheduledTaskDuplicationTest.php index a3dd928051..aa116cd6a5 100644 --- a/tests/Feature/ScheduledTaskDuplicationTest.php +++ b/tests/Feature/ScheduledTaskDuplicationTest.php @@ -309,7 +309,7 @@ public function testTaskNotExecutedIfNextDateInFuture() // Calculate nextDate using the manager $config = json_decode($task->configuration); - $lastExecution = new \DateTime($task->last_execution, new \DateTimeZone('UTC')); + $lastExecution = new \DateTime($task->last_execution, new DateTimeZone('UTC')); $nextDate = $manager->nextDate($today, $config, $lastExecution, null); // nextDate should be 12:55 which is 55 minutes after "today" (12:00) @@ -352,7 +352,7 @@ public function testTaskExecutedIfNextDatePassed() // Calculate nextDate $config = json_decode($task->configuration); - $lastExecution = new \DateTime($task->last_execution, new \DateTimeZone('UTC')); + $lastExecution = new \DateTime($task->last_execution, new DateTimeZone('UTC')); $nextDate = $manager->nextDate($today, $config, $lastExecution, null); // nextDate should be 12:01 which is before "today" (12:30) diff --git a/tests/Feature/Shared/ResourceAssertionsTrait.php b/tests/Feature/Shared/ResourceAssertionsTrait.php index dd65b22734..4fbed6dce9 100644 --- a/tests/Feature/Shared/ResourceAssertionsTrait.php +++ b/tests/Feature/Shared/ResourceAssertionsTrait.php @@ -22,7 +22,7 @@ trait ResourceAssertionsTrait * @param type $query * @param type $expectedMeta * - * @return \Illuminate\Testing\TestResponse + * @return TestResponse */ protected function assertCorrectModelListing($query, $expectedMeta = []) { @@ -56,7 +56,7 @@ protected function assertModelSorting($query, $expectedFirstRow) * @param string $modelClass * @param array $attributes * - * @return \Illuminate\Testing\TestResponse + * @return TestResponse */ protected function assertCorrectModelCreation($modelClass, array $attributes = []) { @@ -84,7 +84,7 @@ protected function assertCorrectModelCreation($modelClass, array $attributes = [ * @param array $attributes * @param array $errors * - * @return \Illuminate\Testing\TestResponse + * @return TestResponse */ protected function assertModelCreationFails($modelClass, array $attributes = [], array $errors = []) { @@ -105,7 +105,7 @@ protected function assertModelCreationFails($modelClass, array $attributes = [], * @param string $id * @param array $includes * - * @return \Illuminate\Testing\TestResponse + * @return TestResponse */ protected function assertModelShow($id, array $includes = []) { @@ -127,7 +127,7 @@ protected function assertModelShow($id, array $includes = []) * * @param type $id * - * @return \Illuminate\Testing\TestResponse + * @return TestResponse */ protected function assertCorrectModelDeletion($id) { @@ -144,7 +144,7 @@ protected function assertCorrectModelDeletion($id) * * @param type $id * - * @return \Illuminate\Testing\TestResponse + * @return TestResponse */ protected function assertModelDeletionFails($id, array $errors = []) { @@ -236,7 +236,7 @@ private function getDataAttributes($row) * Assert that the response has the given status code. * * @param string $expected - * @param \Illuminate\Testing\TestResponse $response + * @param TestResponse $response */ protected function assertStatus($expected, TestResponse $response) { diff --git a/tests/Feature/Upgrade/RemoveMcpSystemSkillsTest.php b/tests/Feature/Upgrade/RemoveMcpSystemSkillsTest.php new file mode 100644 index 0000000000..183062c383 --- /dev/null +++ b/tests/Feature/Upgrade/RemoveMcpSystemSkillsTest.php @@ -0,0 +1,59 @@ +up(); + } + + public function testRemovesSystemSkillsAndKeepsCustomSkills(): void + { + Setting::factory()->create([ + 'key' => McpGuidance::SKILLS_KEY, + 'format' => 'component', + 'config' => [ + ['id' => 'mcp-system-screen-creation-rules', 'slug' => 'screen-creation-rules', 'system' => true], + ['id' => 'flagged-system', 'slug' => 'flagged', 'system' => true], + ['id' => 'skill-1793976475109-l6si55', 'slug' => 'skill-1793976475109-l6si55'], + ['id' => 'custom-1', 'name' => 'Japanese labels', 'slug' => 'japanese-labels', 'content' => 'x'], + ['id' => 'custom-2', 'name' => 'Tone', 'slug' => 'tone', 'content' => 'y', 'scope' => 'screens'], + ], + 'name' => 'Skills', + 'group' => 'MCP', + 'ui' => ['component' => 'McpSkills'], + ]); + + $this->runUpgrade(); + + $skills = Setting::configByKey(McpGuidance::SKILLS_KEY); + $this->assertSame(['custom-1', 'custom-2'], array_column($skills, 'id')); + $this->assertSame('screens', $skills[1]['scope']); + } + + public function testIsIdempotentAndSkipsMissingSetting(): void + { + $this->runUpgrade(); + $this->assertNull(Setting::where('key', McpGuidance::SKILLS_KEY)->first()); + + Setting::factory()->create([ + 'key' => McpGuidance::SKILLS_KEY, + 'format' => 'component', + 'config' => [['id' => 'custom-1', 'slug' => 'a', 'content' => 'x']], + 'name' => 'Skills', + 'group' => 'MCP', + ]); + + $this->runUpgrade(); + $this->runUpgrade(); + + $this->assertCount(1, Setting::configByKey(McpGuidance::SKILLS_KEY)); + } +} diff --git a/tests/Jobs/InstallPluginTest.php b/tests/Jobs/InstallPluginTest.php new file mode 100644 index 0000000000..cd6848a9cb --- /dev/null +++ b/tests/Jobs/InstallPluginTest.php @@ -0,0 +1,107 @@ +shouldReceive('install') + ->once() + ->with( + 'https://github.com/ProcessMaker/package-translations.git', + 'develop', + null, + 7, + null, + null, + ); + + $job = new InstallPlugin( + userId: 7, + url: 'https://github.com/ProcessMaker/package-translations.git', + branch: 'develop', + ); + $job->handle($manager); + + Event::assertDispatched(PluginLog::class, function (PluginLog $event) { + return $event->status === 'starting' + && $event->userId === 7; + }); + } + + public function testHandleInstallsFromZip(): void + { + Event::fake([PluginLog::class]); + + $zipPath = storage_path('app/plugin-uploads/example.zip'); + $manager = Mockery::mock(PluginManager::class); + $manager->shouldReceive('installFromZip') + ->once() + ->with($zipPath, 7); + + $job = new InstallPlugin( + userId: 7, + zipPath: $zipPath, + ); + $job->handle($manager); + + Event::assertDispatched(PluginLog::class, function (PluginLog $event) { + return $event->status === 'starting'; + }); + } + + public function testHandleRevertsAndRethrowsWhenInstallFails(): void + { + Event::fake([PluginLog::class]); + + $manager = Mockery::mock(PluginManager::class); + $manager->shouldReceive('install') + ->once() + ->andThrow(new \RuntimeException('Git clone exceeded the timeout while installing package-plg.')); + $manager->shouldReceive('revertFailedInstall') + ->once() + ->with(7); + + $job = new InstallPlugin( + userId: 7, + url: 'https://github.com/ProcessMaker/package-plg.git', + ); + + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('exceeded the timeout'); + + $job->handle($manager); + } + + public function testFailedBroadcastsError(): void + { + Event::fake([PluginLog::class]); + + $job = new InstallPlugin( + userId: 7, + url: 'https://github.com/ProcessMaker/package-translations.git', + ); + $job->failed(new \RuntimeException( + "The process \"'git' 'clone' 'https://token:secret@github.com/ProcessMaker/package-plg'\" exceeded the timeout of 300 seconds." + )); + + Event::assertDispatched(PluginLog::class, function (PluginLog $event) { + return $event->status === 'error' + && str_contains($event->message, 'exceeded the timeout') + && !str_contains($event->message, 'secret') + && str_contains($event->message, 'https://github.com/ProcessMaker/package-plg') + && $event->userId === 7; + }); + } +} diff --git a/tests/Managers/PluginManagerTest.php b/tests/Managers/PluginManagerTest.php new file mode 100644 index 0000000000..4706c9d457 --- /dev/null +++ b/tests/Managers/PluginManagerTest.php @@ -0,0 +1,857 @@ +pluginsDir = storage_path('plugins'); + if (!is_dir($this->pluginsDir)) { + mkdir($this->pluginsDir, 0755, true); + } + + config([ + 'plugin_manager.supervisorctl_bin' => 'supervisorctl', + 'plugin_manager.supervisorctl_config' => null, + 'plugin_manager.supervisor_restart_target' => 'all', + 'plugin_manager.allow_local_install_path' => true, + ]); + + $this->runtimeReload = Mockery::spy(PluginRuntimeReload::class); + $this->runtimeReload->shouldReceive('recycleLocalRuntime')->byDefault()->andReturn(false); + app()->instance(PluginRuntimeReload::class, $this->runtimeReload); + } + + protected function tearDown(): void + { + $this->tearDownTestPluginManager(); + + parent::tearDown(); + } + + public function tearDownTestPluginManager() + { + if (!$this->pluginsDir) { + return; + } + + foreach (array_merge($this->temporaryPluginDirs(), $this->leftoverToggleDirs()) as $dir) { + if (is_link($dir)) { + unlink($dir); + continue; + } + + if (is_dir($dir) && realpath($dir) !== realpath($this->pluginsDir)) { + $this->deleteDirectory($dir); + } + } + } + + /** + * Toggle renames the folder by adding or removing a leading underscore. + * Remove whichever path is left. + * + * @return list + */ + private function temporaryPluginDirs(): array + { + if (!$this->tempPluginDir || realpath((string) $this->tempPluginDir) === realpath($this->pluginsDir)) { + return [ + $this->pluginsDir . '/plugin-one', + $this->pluginsDir . '/plugin-two', + $this->pluginsDir . '/valid-plugin', + $this->pluginsDir . '/_hidden-plugin', + $this->pluginsDir . '/clone-origin-test', + ]; + } + + $base = basename($this->tempPluginDir); + $parent = dirname($this->tempPluginDir); + $toggled = str_starts_with($base, '_') + ? $parent . '/' . substr($base, 1) + : $parent . '/_' . $base; + + return [$this->tempPluginDir, $toggled]; + } + + /** + * @return list + */ + private function leftoverToggleDirs(): array + { + return array_merge( + glob($this->pluginsDir . '/supervisor-toggle-*') ?: [], + glob($this->pluginsDir . '/_supervisor-toggle-*') ?: [] + ); + } + + public function testInstallExistingRepositoryChecksOutRequestedBranchWithoutMain() + { + $this->setUpTestPluginManager(); + + $repoUrl = 'https://github.com/ProcessMaker/plugin-develop.git'; + $pluginName = 'plugin-develop'; + $pluginPath = $this->pluginsDir . '/' . $pluginName; + + $this->tempPluginDir = $pluginPath; + mkdir($this->tempPluginDir, 0755, true); + file_put_contents( + $this->tempPluginDir . '/composer.json', + json_encode([ + 'name' => 'processmaker/plugin-develop', + 'autoload' => [ + 'psr-4' => [ + 'ProcessMaker\\Plugins\\Develop\\' => 'src/', + ], + ], + ], JSON_PRETTY_PRINT) + ); + + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + + Event::fake([PluginLog::class]); + + $manager = new PluginManager(); + $manager->install($repoUrl, 'develop', null, 1); + + Process::assertRan(fn ($process) => $this->processRunsGitCommand($process, ['git', 'fetch', '--all', '--tags'])); + Process::assertRan(fn ($process) => $this->processRunsGitCommand($process, ['git', 'checkout', 'develop'])); + Process::assertRan(fn ($process) => $this->processRunsGitCommand($process, ['git', 'pull', 'origin', 'develop'])); + Process::assertNotRan(fn ($process) => $this->processRunsGitCommand($process, ['git', 'checkout', 'main'])); + } + + public function testReinstallUsesCurrentBranchForGitPull() + { + $this->setUpTestPluginManager(); + + $pluginName = 'plugin-reinstall-' . uniqid(); + $pluginPath = $this->pluginsDir . '/' . $pluginName; + $this->tempPluginDir = $pluginPath; + + mkdir($pluginPath, 0755, true); + mkdir($pluginPath . '/.git', 0755, true); + file_put_contents( + $pluginPath . '/composer.json', + json_encode([ + 'name' => 'processmaker/' . $pluginName, + 'autoload' => [ + 'psr-4' => [ + 'ProcessMaker\\Plugins\\Reinstall\\' => 'src/', + ], + ], + ], JSON_PRETTY_PRINT) + ); + + Process::fake([ + '*' => Process::result("develop\n", 0), + ]); + + Event::fake([PluginLog::class]); + + $manager = new PluginManager(); + $manager->reinstall($pluginName, 1); + + Process::assertRan(fn ($process) => $this->processRunsGitCommand($process, ['git', 'rev-parse', '--abbrev-ref', 'HEAD'])); + Process::assertRan(fn ($process) => $this->processRunsGitCommand($process, ['git', 'pull', 'origin', 'develop'])); + } + + public function testInstallExistingRepositoryWithTagSkipsBranchCheckoutAndPull() + { + $this->setUpTestPluginManager(); + + $repoUrl = 'https://github.com/ProcessMaker/plugin-tagged.git'; + $pluginName = 'plugin-tagged'; + $pluginPath = $this->pluginsDir . '/' . $pluginName; + + $this->tempPluginDir = $pluginPath; + mkdir($this->tempPluginDir, 0755, true); + file_put_contents( + $this->tempPluginDir . '/composer.json', + json_encode([ + 'name' => 'processmaker/plugin-tagged', + 'autoload' => [ + 'psr-4' => [ + 'ProcessMaker\\Plugins\\Tagged\\' => 'src/', + ], + ], + ], JSON_PRETTY_PRINT) + ); + + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + + Event::fake([PluginLog::class]); + + $manager = new PluginManager(); + $manager->install($repoUrl, null, 'v1.0.0', 1); + + Process::assertRan(fn ($process) => $this->processRunsGitCommand($process, ['git', 'checkout', 'tags/v1.0.0'])); + Process::assertNotRan(fn ($process) => $this->processRunsGitCommand($process, ['git', 'checkout', 'main'])); + Process::assertNotRan(fn ($process) => $this->processRunsGitCommand($process, ['git', 'pull'])); + } + + public function testInstallClonesRepositoryAndValidatesPlugin() + { + $this->setUpTestPluginManager(); + + $repoUrl = 'https://github.com/ProcessMaker/plugin-example.git'; + $pluginName = 'plugin-example'; + $pluginPath = $this->pluginsDir . '/' . $pluginName; + + // Create temporary plugin directory with valid composer.json + $this->tempPluginDir = $pluginPath; + mkdir($this->tempPluginDir, 0755, true); + $composerJson = [ + 'name' => 'processmaker/plugin-example', + 'description' => 'Test plugin', + 'autoload' => [ + 'psr-4' => [ + 'ProcessMaker\\Plugins\\Example\\' => 'src/', + ], + ], + ]; + file_put_contents( + $this->tempPluginDir . '/composer.json', + json_encode($composerJson, JSON_PRETTY_PRINT) + ); + + // Fake Process to return successful results + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + + Event::fake([PluginLog::class]); + + $manager = new PluginManager(); + $manager->install($repoUrl, null, null, 1); + + Event::assertDispatched(PluginLog::class, function ($event) { + return str_contains($event->message, 'installed successfully'); + }); + $this->assertRuntimeReloadPublished(); + } + + public function testInstallValidatesComposerJsonNamespace() + { + $this->setUpTestPluginManager(); + + $repoUrl = 'https://github.com/ProcessMaker/invalid-plugin.git'; + $pluginName = 'invalid-plugin'; + $pluginPath = $this->pluginsDir . '/' . $pluginName; + + // Create temporary plugin directory with invalid composer.json + $this->tempPluginDir = $pluginPath; + mkdir($this->tempPluginDir, 0755, true); + $composerJson = [ + 'name' => 'invalid/plugin', + 'autoload' => [ + 'psr-4' => [ + 'Invalid\\Namespace\\' => 'src/', + ], + ], + ]; + file_put_contents( + $this->tempPluginDir . '/composer.json', + json_encode($composerJson, JSON_PRETTY_PRINT) + ); + + // Fake Process to return successful results + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + + Event::fake([PluginLog::class]); + + $manager = new PluginManager(); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage("Plugin PSR-4 namespace must start with 'ProcessMaker\\Plugins\\'"); + + $manager->install($repoUrl); + } + + public function testInstallRepositoryWithoutCommitsShowsFriendlyMessage(): void + { + $this->setUpTestPluginManager(); + + $this->tempPluginDir = $this->pluginsDir . '/empty-remote-plugin'; + mkdir($this->tempPluginDir . '/.git', 0755, true); + + $this->fakeGit(['git rev-parse --verify HEAD' => Process::result('', 'fatal: Needed a single revision', 128)]); + Event::fake([PluginLog::class]); + + try { + (new PluginManager())->install('https://github.com/acme/empty-remote-plugin.git', null, null, 1); + $this->fail('Install of an empty repository was expected to fail.'); + } catch (RuntimeException $exception) { + $this->assertSame(PluginManager::EMPTY_REPOSITORY_MESSAGE, $exception->getMessage()); + } + + Event::assertDispatched(PluginLog::class, function (PluginLog $event) { + return str_contains($event->message, 'has no plugin code yet'); + }); + } + + public function testInstallRepositoryWithOnlyReadmeAndLicenseShowsFriendlyMessage(): void + { + $this->setUpTestPluginManager(); + + $this->tempPluginDir = $this->pluginsDir . '/readme-only-plugin'; + mkdir($this->tempPluginDir . '/.git', 0755, true); + + $this->fakeGit(['git ls-files' => Process::result("README.md\nLICENSE\n.gitignore\n", '', 0)]); + Event::fake([PluginLog::class]); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('has no plugin code yet'); + + (new PluginManager())->install('https://github.com/acme/readme-only-plugin.git', null, null, 1); + } + + public function testInstallRepositoryWithCodeButNoComposerJsonKeepsOriginalMessage(): void + { + $this->setUpTestPluginManager(); + + $this->tempPluginDir = $this->pluginsDir . '/no-composer-plugin'; + mkdir($this->tempPluginDir . '/.git', 0755, true); + + $this->fakeGit(['git ls-files' => Process::result("README.md\nsrc/Plugin.php\n", '', 0)]); + Event::fake([PluginLog::class]); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('composer.json not found in plugin'); + + (new PluginManager())->install('https://github.com/acme/no-composer-plugin.git', null, null, 1); + } + + public function testCloneOfEmptyRepositoryFailsBeforeBranchCheckoutAndIsRolledBack(): void + { + $this->setUpTestPluginManager(); + + $pluginPath = $this->pluginsDir . '/fresh-empty-plugin'; + $this->tempPluginDir = $pluginPath; + $this->assertDirectoryDoesNotExist($pluginPath); + + // Simulate `git clone` of an empty remote: it succeeds and leaves a .git directory without commits. + Process::fake(function ($process) { + if (is_array($process->command) && ($process->command[1] ?? null) === 'clone') { + mkdir($process->command[3] . '/.git', 0755, true); + } + if (is_array($process->command) && implode(' ', $process->command) === 'git rev-parse --verify HEAD') { + return Process::result('', 'fatal: Needed a single revision', 128); + } + + return Process::result('', exitCode: 0); + }); + Event::fake([PluginLog::class]); + + try { + (new PluginManager())->install('https://github.com/acme/fresh-empty-plugin.git', 'develop', null, 1); + $this->fail('Install of an empty repository was expected to fail.'); + } catch (RuntimeException $exception) { + $this->assertSame(PluginManager::EMPTY_REPOSITORY_MESSAGE, $exception->getMessage()); + } + + Process::assertNotRan(fn ($process) => $this->processRunsGitCommand($process, ['git', 'checkout', 'develop'])); + $this->assertDirectoryDoesNotExist($pluginPath); + } + + /** + * Fake every process as successful, except the given commands (keyed by the space-joined command). + * + * @param array $overrides + */ + private function fakeGit(array $overrides = []): void + { + Process::fake(function ($process) use ($overrides) { + if (is_array($process->command)) { + $command = implode(' ', $process->command); + if (isset($overrides[$command])) { + return $overrides[$command]; + } + } + + return Process::result('', exitCode: 0); + }); + } + + public function testInstallFailureRemovesPluginDirectoryCreatedByTheAttempt(): void + { + $this->setUpTestPluginManager(); + + $sourceName = 'plugin-rollback-' . uniqid(); + $source = sys_get_temp_dir() . '/' . $sourceName; + mkdir($source, 0755, true); + file_put_contents($source . '/composer.json', json_encode([ + 'name' => 'invalid/plugin', + 'autoload' => [ + 'psr-4' => [ + 'Invalid\\Namespace\\' => 'src/', + ], + ], + ])); + + $pluginPath = $this->pluginsDir . '/' . $sourceName; + $this->tempPluginDir = $pluginPath; + + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + Event::fake([PluginLog::class]); + + $manager = new PluginManager(); + + try { + $manager->install($source, null, null, 1); + $this->fail('Install was expected to fail validation.'); + } catch (RuntimeException $exception) { + $this->assertStringContainsString('PSR-4', $exception->getMessage()); + } finally { + $this->deleteDirectory($source); + } + + $this->assertFalse(is_dir($pluginPath) || is_link($pluginPath)); + Event::assertDispatched(PluginLog::class, function (PluginLog $event) { + return str_contains($event->message, 'Removing the incomplete plugin directory'); + }); + } + + public function testUninstallRemovesPluginDirectory() + { + $this->setUpTestPluginManager(); + + $pluginName = 'test-plugin'; + $pluginPath = $this->pluginsDir . '/' . $pluginName; + + // Create temporary plugin directory + $this->tempPluginDir = $pluginPath; + mkdir($this->tempPluginDir, 0755, true); + file_put_contents($this->tempPluginDir . '/test.txt', 'test'); + + Event::fake([PluginLog::class]); + + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + + $manager = new PluginManager(); + $manager->uninstall($pluginName, 1); + + $this->assertFalse(is_dir($pluginPath)); + Event::assertDispatched(PluginLog::class, function ($event) { + return str_contains($event->message, 'uninstalled successfully'); + }); + $this->assertRuntimeReloadPublished(); + } + + public function testUninstallThrowsExceptionForNonExistentPlugin() + { + $this->setUpTestPluginManager(); + + $manager = new PluginManager(); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Plugin not found: non-existent-plugin'); + + $manager->uninstall('non-existent-plugin'); + } + + public function testListReturnsInstalledPlugins() + { + $this->setUpTestPluginManager(); + + // Create test plugin directories + $plugin1Path = $this->pluginsDir . '/plugin-one'; + $plugin2Path = $this->pluginsDir . '/plugin-two'; + $this->tempPluginDir = $this->pluginsDir; + + mkdir($plugin1Path, 0755, true); + mkdir($plugin2Path, 0755, true); + + $composerJson1 = [ + 'name' => 'test/plugin-one', + 'description' => 'First test plugin', + 'autoload' => [ + 'psr-4' => [ + 'ProcessMaker\\Plugins\\One\\' => 'src/', + ], + ], + ]; + + $composerJson2 = [ + 'name' => 'test/plugin-two', + 'description' => 'Second test plugin', + 'autoload' => [ + 'psr-4' => [ + 'ProcessMaker\\Plugins\\Two\\' => 'src/', + ], + ], + ]; + + file_put_contents( + $plugin1Path . '/composer.json', + json_encode($composerJson1, JSON_PRETTY_PRINT) + ); + file_put_contents( + $plugin2Path . '/composer.json', + json_encode($composerJson2, JSON_PRETTY_PRINT) + ); + + // Mock git commands to return null (no git repo) + Process::fake([ + '*' => Process::result(''), + ]); + + $manager = new PluginManager(); + $plugins = $manager->list(); + + $this->assertCount(2, $plugins); + $this->assertEquals('plugin-one', $plugins[0]['name']); + $this->assertEquals('First test plugin', $plugins[0]['description']); + $this->assertEquals('plugin-two', $plugins[1]['name']); + $this->assertEquals('Second test plugin', $plugins[1]['description']); + } + + public function testListIncludesDisabledPlugins() + { + $this->setUpTestPluginManager(); + + $validPluginPath = $this->pluginsDir . '/valid-plugin'; + $hiddenPluginPath = $this->pluginsDir . '/_hidden-plugin'; + $this->tempPluginDir = $this->pluginsDir; + + mkdir($validPluginPath, 0755, true); + mkdir($hiddenPluginPath, 0755, true); + + $composerJson = [ + 'name' => 'test/plugin', + 'description' => 'Test plugin', + 'autoload' => [ + 'psr-4' => [ + 'ProcessMaker\\Plugins\\Test\\' => 'src/', + ], + ], + ]; + + file_put_contents( + $validPluginPath . '/composer.json', + json_encode($composerJson, JSON_PRETTY_PRINT) + ); + file_put_contents( + $hiddenPluginPath . '/composer.json', + json_encode($composerJson, JSON_PRETTY_PRINT) + ); + + Process::fake(); + + $manager = new PluginManager(); + $plugins = $manager->list(); + $pluginsByName = collect($plugins)->keyBy('name'); + + $this->assertCount(2, $plugins); + $this->assertEquals('Enabled', $pluginsByName['valid-plugin']['enabled']); + $this->assertEquals('Disabled', $pluginsByName['hidden-plugin']['enabled']); + } + + public function testArtisanEnvironmentIncludesCurrentTenant() + { + config(['app.multitenancy' => true]); + $this->app->instance('currentTenant', (object) ['id' => 7]); + + $method = new \ReflectionMethod(PluginManager::class, 'artisanEnvironment'); + $environment = $method->invoke(new PluginManager()); + + $this->assertSame(['TENANT' => '7'], $environment); + } + + public function testToggleRebuildsRouteCacheAndRestartsSupervisor() + { + $this->setUpTestPluginManager(); + + $pluginName = 'toggle-plugin'; + $pluginPath = $this->pluginsDir . '/' . $pluginName; + $this->tempPluginDir = $this->pluginsDir . '/_' . $pluginName; + mkdir($pluginPath, 0755, true); + + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + + $manager = new PluginManager(); + $enabled = $manager->toggle($pluginName); + + $this->assertFalse($enabled); + $this->assertFalse(is_dir($pluginPath)); + $this->assertTrue(is_dir($this->pluginsDir . '/_' . $pluginName)); + + $this->assertProcessRanCommand('route:cache'); + $this->assertRuntimeReloadPublished(); + } + + public function testToggleEnableRestartsSupervisor() + { + $this->setUpTestPluginManager(); + + $pluginName = 'toggle-plugin'; + $disabledPath = $this->pluginsDir . '/_' . $pluginName; + $this->tempPluginDir = $this->pluginsDir . '/' . $pluginName; + mkdir($disabledPath, 0755, true); + + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + + $manager = new PluginManager(); + $enabled = $manager->toggle($pluginName); + + $this->assertTrue($enabled); + $this->assertTrue(is_dir($this->pluginsDir . '/' . $pluginName)); + $this->assertRuntimeReloadPublished(); + } + + public function testScheduleSupervisorRestartUsesConfigFileWhenSet(): void + { + config([ + 'plugin_manager.supervisorctl_bin' => 'supervisorctl', + 'plugin_manager.supervisorctl_config' => '/tmp/processmaker-supervisord.conf', + 'plugin_manager.supervisor_restart_target' => 'all', + 'plugin_manager.supervisor_restart_delay' => 5, + ]); + + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + + $this->assertTrue((new PluginRuntimeReload())->scheduleSupervisorRestart()); + $this->assertSupervisorRestartRan('/tmp/processmaker-supervisord.conf'); + } + + public function testLocalInstallReplacesLeftoverSymlinkWithCopy(): void + { + $this->setUpTestPluginManager(); + + $pluginName = 'local-symlink-plugin-' . uniqid(); + $sourceDir = sys_get_temp_dir() . '/' . $pluginName; + $pluginPath = $this->pluginsDir . '/' . $pluginName; + + mkdir($sourceDir, 0755, true); + mkdir($sourceDir . '/src', 0755, true); + file_put_contents($sourceDir . '/composer.json', json_encode([ + 'name' => 'processmaker/' . $pluginName, + 'autoload' => [ + 'psr-4' => [ + 'ProcessMaker\\Plugins\\SymlinkTest\\' => 'src/', + ], + ], + ], JSON_PRETTY_PRINT)); + file_put_contents($sourceDir . '/source-only.marker', 'source'); + + $this->assertTrue(symlink($sourceDir, $pluginPath)); + $this->assertTrue(is_link($pluginPath)); + + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + Event::fake([PluginLog::class]); + + $manager = new PluginManager(); + $manager->install($sourceDir, null, null, 1); + + $this->assertFalse(is_link($pluginPath)); + $this->assertTrue(is_dir($pluginPath)); + $this->assertFileExists($pluginPath . '/source-only.marker'); + + if (is_dir($pluginPath)) { + $this->deleteDirectory($pluginPath); + } + if (is_dir($sourceDir)) { + $this->deleteDirectory($sourceDir); + } + } + + public function testRunCommandLogsSuccessfulOutputOnce() + { + Process::fake([ + '*' => Process::result("Routes cached successfully.\n", exitCode: 0), + ]); + Event::fake([PluginLog::class]); + + $method = new \ReflectionMethod(PluginManager::class, 'runCommand'); + $method->invoke(new PluginManager(), 'route:cache', 'test-plugin', 1); + + Event::assertDispatchedTimes(PluginLog::class, 1); + Event::assertDispatched(PluginLog::class, function (PluginLog $event) { + return str_contains($event->message, 'Plugin route:cache command output'); + }); + } + + public function testStripEmbeddedCredentialsFromHttpUrlRemovesTokenUserinfo() + { + $manager = new PluginManager(); + $method = new \ReflectionMethod($manager, 'stripEmbeddedCredentialsFromHttpUrl'); + $method->setAccessible(true); + + $this->assertSame( + 'https://github.com/org/repo.git', + $method->invoke($manager, 'https://ghp_xxx@github.com/org/repo.git') + ); + $this->assertSame( + 'https://github.com/org/repo.git', + $method->invoke($manager, 'https://user:secret@github.com/org/repo.git') + ); + } + + public function testRedactHttpUserInfoFromString() + { + $dirty = 'clone failed for https://ghp_xxx@github.com/org/repo.git'; + $this->assertSame( + 'clone failed for https://github.com/org/repo.git', + PluginManager::redactHttpUserInfoFromString($dirty) + ); + } + + public function testCloneRepositorySetsStrippedOriginAfterSuccess() + { + $this->setUpTestPluginManager(); + + $dest = $this->pluginsDir . '/clone-origin-test'; + mkdir($dest, 0755, true); + + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + + $manager = new PluginManager(); + $method = new \ReflectionMethod($manager, 'cloneRepository'); + $method->setAccessible(true); + + $authUrl = 'https://ghp_xxx@github.com/org/repo.git'; + $canonical = 'https://github.com/org/repo.git'; + + $method->invoke($manager, $authUrl, $dest, 'repo', null, $canonical); + + Process::assertRan(fn ($process) => is_array($process->command) + && $process->command === ['git', 'clone', $authUrl, $dest]); + Process::assertRan(fn ($process) => is_array($process->command) + && $process->command === ['git', 'remote', 'set-url', 'origin', $canonical]); + } + + private function assertProcessRanCommand(string $artisanCommand): void + { + Process::assertRan(function ($process) use ($artisanCommand) { + $command = is_array($process->command) + ? implode(' ', $process->command) + : (string) $process->command; + + return str_contains($command, $artisanCommand); + }); + } + + private function assertRuntimeReloadPublished(): void + { + $this->runtimeReload->shouldHaveReceived('recycleLocalRuntime')->atLeast()->once(); + $this->runtimeReload->shouldHaveReceived('publish')->atLeast()->once(); + } + + public function testPluginChangeSkipsRedisWhenLocalRecycleSucceeds(): void + { + $this->setUpTestPluginManager(); + $this->runtimeReload->shouldReceive('recycleLocalRuntime')->andReturn(true); + + $pluginName = 'recycle-ok-plugin'; + $disabledPath = $this->pluginsDir . '/_' . $pluginName; + $this->tempPluginDir = $this->pluginsDir . '/' . $pluginName; + mkdir($disabledPath, 0755, true); + + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + + $manager = new PluginManager(); + $manager->toggle($pluginName); + + $this->runtimeReload->shouldHaveReceived('recycleLocalRuntime')->once(); + $this->runtimeReload->shouldNotHaveReceived('publish'); + } + + private function assertSupervisorRestartRan(?string $configFile = null): void + { + $bin = config('plugin_manager.supervisorctl_bin', 'supervisorctl'); + $target = config('plugin_manager.supervisor_restart_target', 'all'); + $configFile = $configFile ?? config('plugin_manager.supervisorctl_config'); + + $expected = [$bin]; + if ($configFile) { + $expected[] = '-c'; + $expected[] = $configFile; + } + $expected[] = 'restart'; + $expected[] = $target; + + Process::assertRan(function ($process) use ($expected, $configFile) { + if (!is_array($process->command)) { + return false; + } + + $command = implode(' ', $process->command); + + if (!str_contains($command, 'nohup')) { + return false; + } + + foreach ($expected as $part) { + if (!str_contains($command, $part)) { + return false; + } + } + + return $configFile === null || str_contains($command, (string) $configFile); + }); + } + + private function processRunsGitCommand($process, array $expectedCommand): bool + { + if (!is_array($process->command)) { + return false; + } + + return $process->command === $expectedCommand; + } + + private function deleteDirectory($dir) + { + if (!is_dir($dir)) { + return; + } + + $files = array_diff(scandir($dir), ['.', '..']); + foreach ($files as $file) { + $path = $dir . '/' . $file; + if (is_dir($path)) { + $this->deleteDirectory($path); + } else { + unlink($path); + } + } + rmdir($dir); + } +} diff --git a/tests/Managers/ScreenBuilderManagerTest.php b/tests/Managers/ScreenBuilderManagerTest.php new file mode 100644 index 0000000000..042cfd9092 --- /dev/null +++ b/tests/Managers/ScreenBuilderManagerTest.php @@ -0,0 +1,213 @@ + */ + private array $pluginDirsToRemove = []; + + /** @var list */ + private array $publicAssetPaths = []; + + /** @var list */ + private array $tenantPublicAssetPaths = []; + + protected function setUp(): void + { + chdir(realpath(__DIR__ . '/../..')); + parent::setUp(); + + $this->pluginsDir = storage_path('plugins'); + if (!is_dir($this->pluginsDir)) { + mkdir($this->pluginsDir, 0755, true); + } + } + + protected function tearDown(): void + { + foreach ($this->pluginDirsToRemove as $dir) { + if (is_dir($dir)) { + $this->deleteDirectory($dir); + } + } + foreach ($this->publicAssetPaths as $path) { + if (is_file($path)) { + unlink($path); + } + } + foreach ($this->tenantPublicAssetPaths as $path) { + if (is_dir($path)) { + $this->deleteDirectory($path); + } elseif (is_file($path)) { + unlink($path); + } + } + + chdir(realpath(__DIR__ . '/../..')); + + parent::tearDown(); + } + + public function testStoragePluginScreenBuilderScripts(): void + { + $enabledPackage = 'test-plg-plugin-' . uniqid(); + $enabledDir = $this->pluginsDir . '/' . $enabledPackage; + $this->pluginDirsToRemove[] = $enabledDir; + mkdir($enabledDir, 0755, true); + file_put_contents($enabledDir . '/composer.json', json_encode([ + 'name' => 'processmaker/' . $enabledPackage, + ])); + $this->touchPublicAsset($enabledPackage, 'screen-builder-form-components.js'); + + $manager = new ScreenBuilderManager(); + $manager->addPackageScripts('FORM'); + $scripts = $manager->getScripts(); + $this->assertTrue($this->scriptsContainPath( + $scripts, + '/vendor/processmaker/packages/' . $enabledPackage . '/js/screen-builder-form-components.js' + )); + + $disabledPackage = 'disabled-plg-plugin-' . uniqid(); + $disabledDir = $this->pluginsDir . '/_' . $disabledPackage; + $this->pluginDirsToRemove[] = $disabledDir; + mkdir($disabledDir, 0755, true); + file_put_contents($disabledDir . '/composer.json', json_encode([ + 'name' => 'processmaker/' . $disabledPackage, + ])); + $this->touchPublicAsset($disabledPackage, 'screen-builder-form-components.js'); + + $managerDisabled = new ScreenBuilderManager(); + $managerDisabled->addPackageScripts('FORM'); + $disabledScripts = $managerDisabled->getScripts(); + $this->assertFalse($this->scriptsContainPath( + $disabledScripts, + '/vendor/processmaker/packages/' . $disabledPackage . '/js/screen-builder-form-components.js' + )); + + $displayOnlyPackage = 'test-plg-display-only-' . uniqid(); + $displayDir = $this->pluginsDir . '/' . $displayOnlyPackage; + $this->pluginDirsToRemove[] = $displayDir; + mkdir($displayDir, 0755, true); + file_put_contents($displayDir . '/composer.json', json_encode([ + 'name' => 'processmaker/' . $displayOnlyPackage, + ])); + $this->touchPublicAsset($displayOnlyPackage, 'screen-builder-form-components.js'); + + $managerDisplay = new ScreenBuilderManager(); + $managerDisplay->addPackageScripts('DISPLAY'); + $displayScripts = $managerDisplay->getScripts(); + $this->assertFalse($this->scriptsContainPath( + $displayScripts, + '/vendor/processmaker/packages/' . $displayOnlyPackage . '/js/screen-builder-form-components.js' + )); + + $folderName = 'my-plugin-folder-' . uniqid(); + $resolvedName = 'resolved-plg-name-' . uniqid(); + $folderDir = $this->pluginsDir . '/' . $folderName; + $this->pluginDirsToRemove[] = $folderDir; + mkdir($folderDir, 0755, true); + file_put_contents($folderDir . '/composer.json', json_encode([ + 'name' => 'processmaker/' . $resolvedName, + ])); + $this->touchPublicAsset($resolvedName, 'screen-builder-form-components.js'); + + $managerResolved = new ScreenBuilderManager(); + $managerResolved->addPackageScripts('FORM'); + $resolvedScripts = $managerResolved->getScripts(); + $this->assertTrue($this->scriptsContainPath( + $resolvedScripts, + '/vendor/processmaker/packages/' . $resolvedName . '/js/screen-builder-form-components.js' + )); + + config(['app.multitenancy' => true]); + config(['plugin_manager.tenant_plugin_assets_enabled' => true]); + $this->app->instance('currentTenant', (object) ['id' => 7]); + + $tenantPackage = 'tenant-sb-plugin-' . uniqid(); + $tenantDir = $this->pluginsDir . '/' . $tenantPackage; + $this->pluginDirsToRemove[] = $tenantDir; + mkdir($tenantDir, 0755, true); + file_put_contents($tenantDir . '/composer.json', json_encode([ + 'name' => 'processmaker/' . $tenantPackage, + ])); + $this->touchTenantPublicAsset(7, $tenantPackage, 'screen-builder-form-components.js'); + + $managerTenant = new ScreenBuilderManager(); + $managerTenant->addPackageScripts('FORM'); + $tenantScripts = $managerTenant->getScripts(); + $tenantWebPath = PluginVendorAssets::webPath( + $tenantPackage, + '/js/screen-builder-form-components.js' + ); + $this->assertTrue($this->scriptsContainPath($tenantScripts, $tenantWebPath)); + foreach ($tenantScripts as $entry) { + if (str_starts_with($entry, $tenantWebPath)) { + $this->assertStringContainsString('?t=', $entry); + break; + } + } + } + + private function touchTenantPublicAsset(int $tenantId, string $packageName, string $fileName): string + { + $dir = PluginVendorAssets::tenantPackageRoot($tenantId, $packageName) . '/js'; + if (!is_dir($dir)) { + mkdir($dir, 0755, true); + } + $path = $dir . '/' . $fileName; + file_put_contents($path, '// tenant test asset'); + $this->tenantPublicAssetPaths[] = PluginVendorAssets::tenantPackageRoot($tenantId, $packageName); + + return $path; + } + + private function touchPublicAsset(string $packageName, string $fileName): string + { + $dir = public_path('vendor/processmaker/packages/' . $packageName . '/js'); + if (!is_dir($dir)) { + mkdir($dir, 0755, true); + } + $path = $dir . '/' . $fileName; + file_put_contents($path, '// test asset'); + $this->publicAssetPaths[] = $path; + + return $path; + } + + private function scriptsContainPath(array $scripts, string $path): bool + { + foreach ($scripts as $script) { + if (str_starts_with($script, $path)) { + return true; + } + } + + return false; + } + + private function deleteDirectory(string $directory): void + { + if (!is_dir($directory)) { + return; + } + + $files = array_diff(scandir($directory), ['.', '..']); + foreach ($files as $file) { + $path = $directory . '/' . $file; + if (is_dir($path) && !is_link($path)) { + $this->deleteDirectory($path); + } else { + unlink($path); + } + } + + rmdir($directory); + } +} diff --git a/tests/Model/PluginTest.php b/tests/Model/PluginTest.php new file mode 100644 index 0000000000..f0dac6c99c --- /dev/null +++ b/tests/Model/PluginTest.php @@ -0,0 +1,141 @@ +tempDir = sys_get_temp_dir() . '/plugin-test-' . uniqid(); + mkdir($this->tempDir, 0755, true); + } + + public function tearDownTestPlugin() + { + if ($this->tempDir && is_dir($this->tempDir)) { + $this->deleteDirectory($this->tempDir); + } + } + + public function testFromPathCreatesPluginInstance() + { + $this->setUpTestPlugin(); + $plugin = Plugin::fromPath($this->tempDir); + + $this->assertInstanceOf(Plugin::class, $plugin); + $this->assertEquals(basename($this->tempDir), $plugin->getName()); + $this->assertEquals($this->tempDir, $plugin->getPath()); + } + + public function testFromPathThrowsExceptionForNonExistentDirectory() + { + $this->expectException(RuntimeException::class); + Plugin::fromPath('/non/existent/path'); + } + + public function testGetComposerJsonReadsAndParsesFile() + { + $this->setUpTestPlugin(); + $composerJson = [ + 'name' => 'test/plugin', + 'description' => 'Test plugin', + 'autoload' => [ + 'psr-4' => [ + 'ProcessMaker\\Plugins\\Test\\' => 'src/', + ], + ], + ]; + + file_put_contents( + $this->tempDir . '/composer.json', + json_encode($composerJson, JSON_PRETTY_PRINT) + ); + + $plugin = Plugin::fromPath($this->tempDir); + $result = $plugin->getComposerJson(); + + $this->assertEquals($composerJson, $result); + } + + public function testGetComposerJsonThrowsExceptionForMissingFile() + { + $this->setUpTestPlugin(); + $plugin = Plugin::fromPath($this->tempDir); + + $this->expectException(RuntimeException::class); + $plugin->getComposerJson(); + } + + public function testGetComposerJsonThrowsExceptionForInvalidJson() + { + $this->setUpTestPlugin(); + file_put_contents($this->tempDir . '/composer.json', '{ invalid json }'); + + $plugin = Plugin::fromPath($this->tempDir); + + $this->expectException(RuntimeException::class); + $plugin->getComposerJson(); + } + + public function testGetDescriptionReturnsDescriptionFromComposerJson() + { + $this->setUpTestPlugin(); + $composerJson = [ + 'name' => 'test/plugin', + 'description' => 'Test plugin description', + ]; + + file_put_contents( + $this->tempDir . '/composer.json', + json_encode($composerJson, JSON_PRETTY_PRINT) + ); + + $plugin = Plugin::fromPath($this->tempDir); + $this->assertEquals('Test plugin description', $plugin->getDescription()); + } + + public function testGetDescriptionReturnsNullWhenMissing() + { + $this->setUpTestPlugin(); + $composerJson = ['name' => 'test/plugin']; + + file_put_contents( + $this->tempDir . '/composer.json', + json_encode($composerJson, JSON_PRETTY_PRINT) + ); + + $plugin = Plugin::fromPath($this->tempDir); + $this->assertNull($plugin->getDescription()); + } + + public function testGetNameReturnsDirectoryName() + { + $this->setUpTestPlugin(); + $plugin = Plugin::fromPath($this->tempDir); + $this->assertEquals(basename($this->tempDir), $plugin->getName()); + } + + private function deleteDirectory($dir) + { + if (!is_dir($dir)) { + return; + } + + $files = array_diff(scandir($dir), ['.', '..']); + foreach ($files as $file) { + $path = $dir . '/' . $file; + if (is_dir($path)) { + $this->deleteDirectory($path); + } else { + unlink($path); + } + } + rmdir($dir); + } +} diff --git a/tests/ScriptExecutors/BuildScriptExecutorsTest.php b/tests/ScriptExecutors/BuildScriptExecutorsTest.php index 91597623cd..00a2096999 100644 --- a/tests/ScriptExecutors/BuildScriptExecutorsTest.php +++ b/tests/ScriptExecutors/BuildScriptExecutorsTest.php @@ -8,7 +8,6 @@ class BuildScriptExecutorsTest extends TestCase { - public function testBuildScriptExecutorsDockerfile() { $scriptExecutor = ScriptExecutor::factory()->create([ @@ -19,7 +18,7 @@ public function testBuildScriptExecutorsDockerfile() $code = $builder->getDockerfileContent($scriptExecutor); // Check the $code contains 'WORKDIR /opt/executor/src' - $expectedCode = <<addScript(new HtmlString('/vendor/x/js/modeler-test.js?id=1')); + $manager->addScript('/vendor/x/js/modeler-test.js?id=1'); + $manager->addScript('/vendor/x/js/modeler-test.js?id=1', ['type' => 'module']); + $manager->addScript('/vendor/x/js/modeler-test.js?id=2'); + + $srcs = array_column($manager->getScriptWithParams(), 'src'); + $matching = array_values(array_filter($srcs, fn ($src) => str_contains((string) $src, '/x/js/modeler-test.js'))); + + $this->assertCount(2, $matching); + $this->assertSame( + ['/vendor/x/js/modeler-test.js?id=1', '/vendor/x/js/modeler-test.js?id=2'], + array_map('strval', $matching) + ); + $this->assertCount(count($manager->getScripts()), $manager->getScriptWithParams()); + } +} diff --git a/tests/unit/Managers/PluginManagerTenantAssetsTest.php b/tests/unit/Managers/PluginManagerTenantAssetsTest.php new file mode 100644 index 0000000000..6b8295e3f6 --- /dev/null +++ b/tests/unit/Managers/PluginManagerTenantAssetsTest.php @@ -0,0 +1,71 @@ + true]); + config(['plugin_manager.tenant_plugin_assets_enabled' => true]); + $this->app->instance('currentTenant', (object) ['id' => 6]); + + $pluginDir = storage_path('plugins/pm-tenant-assets-' . uniqid()); + mkdir($pluginDir, 0755, true); + file_put_contents($pluginDir . '/composer.json', json_encode([ + 'name' => 'processmaker/tenant-assets-plugin', + ])); + mkdir($pluginDir . '/public/js', 0755, true); + file_put_contents($pluginDir . '/public/js/app.js', '// published by install hook'); + + $manager = new PluginManager(); + $publish = new ReflectionMethod($manager, 'publishTenantPluginAssetsIfApplicable'); + $publish->invoke($manager, $pluginDir, 'tenant-assets-plugin', null); + + $published = PluginVendorAssets::tenantPackageRoot(6, 'tenant-assets-plugin') . '/js/app.js'; + $this->assertFileExists($published); + + $remove = new ReflectionMethod($manager, 'removeTenantPluginAssetsIfApplicable'); + $remove->invoke($manager, $pluginDir, 'tenant-assets-plugin', null); + $this->assertFileDoesNotExist($published); + + config(['app.multitenancy' => false]); + $offDir = storage_path('plugins/pm-tenant-assets-off-' . uniqid()); + mkdir($offDir . '/public/js', 0755, true); + file_put_contents($offDir . '/composer.json', json_encode([ + 'name' => 'processmaker/off-tenant-plugin', + ])); + file_put_contents($offDir . '/public/js/app.js', '// noop'); + $publish->invoke($manager, $offDir, 'off-tenant-plugin', null); + $this->assertFileDoesNotExist( + PluginVendorAssets::tenantPackageRoot(6, 'off-tenant-plugin') . '/js/app.js' + ); + + $this->deleteDirectory($pluginDir); + $this->deleteDirectory($offDir); + } + + private function deleteDirectory(string $dir): void + { + if (!is_dir($dir)) { + return; + } + foreach (scandir($dir) ?: [] as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } + $path = $dir . DIRECTORY_SEPARATOR . $entry; + if (is_dir($path)) { + $this->deleteDirectory($path); + } else { + unlink($path); + } + } + rmdir($dir); + } +} diff --git a/tests/unit/Managers/TenantPluginAssetPublisherTest.php b/tests/unit/Managers/TenantPluginAssetPublisherTest.php new file mode 100644 index 0000000000..516c6bc687 --- /dev/null +++ b/tests/unit/Managers/TenantPluginAssetPublisherTest.php @@ -0,0 +1,62 @@ +deleteTree($tenantDir); + + $pluginDir = storage_path('plugins/tenant-assets-test-' . uniqid()); + mkdir($pluginDir, 0755, true); + file_put_contents($pluginDir . '/composer.json', json_encode(['name' => 'processmaker/test-tenant-pkg'])); + + $publisher = new TenantPluginAssetPublisher(); + $destination = PluginVendorAssets::tenantPackageRoot(self::TENANT_ID, 'test-tenant-pkg'); + + $this->assertFalse($publisher->publishPlugin($pluginDir, self::TENANT_ID)); + $this->assertDirectoryDoesNotExist($destination); + + mkdir($pluginDir . '/public/js', 0755, true); + file_put_contents($pluginDir . '/public/js/app.js', 'console.log("v1");'); + file_put_contents($pluginDir . '/public/mix-manifest.json', '{"\/js\/app.js":"\/js\/app.js?id=1"}'); + + $this->assertTrue($publisher->publishPlugin($pluginDir, self::TENANT_ID)); + $this->assertSame('console.log("v1");', file_get_contents($destination . '/js/app.js')); + $this->assertFileExists($destination . '/mix-manifest.json'); + $this->assertDirectoryDoesNotExist(public_path('vendor/processmaker/packages/test-tenant-pkg')); + + file_put_contents($pluginDir . '/public/js/app.js', 'console.log("v2");'); + $this->assertTrue($publisher->publishPlugin($pluginDir, self::TENANT_ID)); + $this->assertSame('console.log("v2");', file_get_contents($destination . '/js/app.js')); + + $publisher->removePublishedPlugin($pluginDir, self::TENANT_ID); + $this->assertDirectoryDoesNotExist($destination); + + $this->deleteTree($pluginDir); + $this->deleteTree($tenantDir); + } + + private function deleteTree(string $dir): void + { + if (!is_dir($dir)) { + return; + } + foreach (scandir($dir) ?: [] as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } + $path = $dir . DIRECTORY_SEPARATOR . $entry; + is_dir($path) ? $this->deleteTree($path) : unlink($path); + } + rmdir($dir); + } +} diff --git a/tests/unit/Mcp/ProcessBpmnValidatorPortableRefsTest.php b/tests/unit/Mcp/ProcessBpmnValidatorPortableRefsTest.php new file mode 100644 index 0000000000..919648c27a --- /dev/null +++ b/tests/unit/Mcp/ProcessBpmnValidatorPortableRefsTest.php @@ -0,0 +1,95 @@ + + + + + node_4 + + + node_4 + node_5 + + + node_5 + + + + + + + + + + + + + + +XML; + + $result = (new ProcessBpmnValidator())->validate($bpmn); + + $this->assertFalse($result['ok']); + $codes = array_column($result['errors'], 'code'); + $this->assertContains('unresolved_screen_ref', $codes); + } + + public function testNumericScreenRefPassesPortableCheck(): void + { + $bpmn = <<<'XML' + + + + + node_4 + + + node_4 + node_5 + + + node_5 + + + + + + + + + + + + + + +XML; + + $result = (new ProcessBpmnValidator())->validate($bpmn); + $codes = array_column($result['errors'], 'code'); + $this->assertNotContains('unresolved_screen_ref', $codes); + } +} diff --git a/tests/unit/MetricsServiceTest.php b/tests/unit/MetricsServiceTest.php index c215543b72..9b02765e0a 100644 --- a/tests/unit/MetricsServiceTest.php +++ b/tests/unit/MetricsServiceTest.php @@ -15,7 +15,6 @@ use ReflectionClass; use Tests\TestCase; - class MetricsServiceTest extends TestCase { /** @@ -47,7 +46,7 @@ public function testCounterRegistrationAndIncrement(): void $counter = $this->metricsService->counter('test_counter', 'Test Counter', ['label1']); // Assert the counter is registered - $this->assertInstanceOf(\Prometheus\Counter::class, $counter); + $this->assertInstanceOf(Counter::class, $counter); // Increment the counter and assert the value $counter->inc(['value1']); @@ -86,7 +85,7 @@ public function testHistogramRegistrationAndObserve(): void ); // Assert the histogram is registered - $this->assertInstanceOf(\Prometheus\Histogram::class, $histogram); + $this->assertInstanceOf(Histogram::class, $histogram); // Observe a value and assert it is recorded $histogram->observe(0.5, ['value1']); @@ -115,7 +114,7 @@ public function testDefaultNamespace(): void $counter = $this->metricsService->counter('namespace_test'); // Assert default namespace is applied - $this->assertInstanceOf(\Prometheus\Counter::class, $counter); + $this->assertInstanceOf(Counter::class, $counter); $counter->inc(); $samples = $this->metricsService->renderMetrics(); @@ -134,6 +133,7 @@ public function testSetGaugeValue(): void $this->assertStringContainsString('test_set_gauge', $samples); $this->assertStringContainsString('5', $samples); } + /** * Test that counterInc calls Metrics::counter() and then inc() with the correct labels. */ diff --git a/tests/unit/ProcessMaker/Multitenancy/Services/OctaneTenantRuntimeSyncTest.php b/tests/unit/ProcessMaker/Multitenancy/Services/OctaneTenantRuntimeSyncTest.php new file mode 100644 index 0000000000..430eca61a6 --- /dev/null +++ b/tests/unit/ProcessMaker/Multitenancy/Services/OctaneTenantRuntimeSyncTest.php @@ -0,0 +1,186 @@ +supervisorDir = sys_get_temp_dir() . '/pm-octane-sync-sup-' . uniqid(); + $this->edgeCaddyfile = sys_get_temp_dir() . '/pm-octane-sync-edge-' . uniqid() . '.caddy'; + $this->appDirectory = sys_get_temp_dir() . '/pm-octane-sync-app-' . uniqid(); + + File::makeDirectory($this->supervisorDir, 0755, true); + File::makeDirectory($this->appDirectory, 0755, true); + + config([ + 'app.multitenancy' => false, + 'octane_tenants.supervisor_dir' => $this->supervisorDir, + 'octane_tenants.edge_caddyfile' => $this->edgeCaddyfile, + 'octane_tenants.frankenphp_binary' => $this->appDirectory . '/frankenphp', + 'octane_tenants.app_directory' => $this->appDirectory, + 'octane_tenants.supervisor_user' => 'nginx', + 'octane_tenants.php_binary' => 'php', + 'octane_tenants.edge_host' => '127.0.0.1', + 'octane_tenants.edge_port' => 8001, + 'octane_tenants.tenant_host' => '127.0.0.1', + 'octane_tenants.tenant_port_base' => 8100, + 'octane_tenants.tenant_admin_port_base' => 9100, + 'octane_tenants.supervisorctl_bin' => 'supervisorctl', + 'octane_tenants.supervisorctl_config' => null, + ]); + } + + protected function tearDown(): void + { + File::deleteDirectory($this->supervisorDir); + File::deleteDirectory($this->appDirectory); + if (is_file($this->edgeCaddyfile)) { + unlink($this->edgeCaddyfile); + } + + parent::tearDown(); + } + + public function test_single_mode_writes_octane_ini_and_removes_tenant_runtime_files(): void + { + File::put($this->supervisorDir . '/octane-edge.ini', 'old-edge'); + File::put($this->supervisorDir . '/octane-tenant-1.ini', 'old-tenant'); + File::put($this->edgeCaddyfile, 'old-caddy'); + + $result = (new OctaneTenantRuntimeSync())->sync(); + + $this->assertSame('single', $result['mode']); + $this->assertFileExists($this->supervisorDir . '/octane.ini'); + $this->assertFileDoesNotExist($this->supervisorDir . '/octane-edge.ini'); + $this->assertFileDoesNotExist($this->supervisorDir . '/octane-tenant-1.ini'); + $this->assertFileDoesNotExist($this->edgeCaddyfile); + + $octaneIni = file_get_contents($this->supervisorDir . '/octane.ini'); + $this->assertStringContainsString(OctaneTenantRuntimeSync::MANAGED_MARKER, $octaneIni); + $this->assertStringContainsString('[program:octane]', $octaneIni); + $this->assertStringContainsString('--port=8001', $octaneIni); + $this->assertStringNotContainsString('TENANT=', $octaneIni); + } + + public function test_multitenant_mode_writes_edge_and_per_tenant_programs(): void + { + config(['app.multitenancy' => true]); + File::put($this->supervisorDir . '/octane.ini', 'legacy-single'); + + $sync = new class extends OctaneTenantRuntimeSync + { + protected function tenants(): Collection + { + return collect([ + $this->fakeTenant(1, 'tenant-one.example.com'), + $this->fakeTenant(2, 'tenant-two.example.com'), + ]); + } + + private function fakeTenant(int $id, string $domain): Tenant + { + $tenant = new Tenant(); + $tenant->forceFill([ + 'id' => $id, + 'name' => 'Tenant ' . $id, + 'domain' => $domain, + ]); + + return $tenant; + } + }; + + $result = $sync->sync(); + + $this->assertSame('multitenant', $result['mode']); + $this->assertFileDoesNotExist($this->supervisorDir . '/octane.ini'); + $this->assertFileExists($this->supervisorDir . '/octane-edge.ini'); + $this->assertFileExists($this->supervisorDir . '/octane-tenant-1.ini'); + $this->assertFileExists($this->supervisorDir . '/octane-tenant-2.ini'); + $this->assertFileExists($this->edgeCaddyfile); + + $edge = file_get_contents($this->edgeCaddyfile); + $this->assertStringContainsString('auto_https off', $edge); + $this->assertStringContainsString(':8001 {', $edge); + $this->assertStringContainsString('protocols h1 h2', $edge); + $this->assertStringContainsString('host tenant-one.example.com', $edge); + $this->assertStringContainsString('reverse_proxy 127.0.0.1:8101', $edge); + $this->assertStringContainsString('flush_interval -1', $edge); + $this->assertStringContainsString('reverse_proxy 127.0.0.1:8102', $edge); + + $edgeIni = file_get_contents($this->supervisorDir . '/octane-edge.ini'); + $this->assertStringContainsString('[program:octane-edge]', $edgeIni); + $this->assertStringContainsString('frankenphp run --config', $edgeIni); + $this->assertStringContainsString($this->edgeCaddyfile, $edgeIni); + + $tenant1 = file_get_contents($this->supervisorDir . '/octane-tenant-1.ini'); + $this->assertStringContainsString('[program:octane-tenant-1]', $tenant1); + $this->assertStringContainsString('--port=8101', $tenant1); + $this->assertStringContainsString('--admin-port=9101', $tenant1); + $this->assertStringContainsString('TENANT="1"', $tenant1); + $this->assertStringContainsString('--max-requests=500', $tenant1); + $this->assertStringNotContainsString('ENV_OCTANE_MAX_REQUESTS', $tenant1); + + $this->assertCount(2, $result['tenants']); + } + + public function test_dry_run_does_not_write_files(): void + { + $result = (new OctaneTenantRuntimeSync())->sync(dryRun: true); + + $this->assertSame('single', $result['mode']); + $this->assertFileDoesNotExist($this->supervisorDir . '/octane.ini'); + $this->assertContains($this->supervisorDir . '/octane.ini', $result['written']); + } + + public function test_apply_supervisor_runs_reread_and_update(): void + { + Process::fake([ + '*' => Process::result('ok', exitCode: 0), + ]); + + $output = (new OctaneTenantRuntimeSync())->applySupervisor(); + + $this->assertStringContainsString('ok', $output); + Process::assertRan(function ($process) { + $command = is_array($process->command) ? $process->command : []; + + return ($command[0] ?? null) === 'supervisorctl' + && in_array(($command[1] ?? null), ['reread', 'update'], true); + }); + } + + public function test_edge_caddyfile_renderer_handles_empty_tenant_list(): void + { + $contents = (new OctaneTenantRuntimeSync())->renderEdgeCaddyfile([]); + + $this->assertStringContainsString('respond "No tenants configured" 503', $contents); + } + + public function test_artisan_command_dry_run_succeeds_in_single_mode(): void + { + $this->artisan('tenants:octane-sync', ['--dry-run' => true]) + ->expectsOutputToContain('Mode: single') + ->assertSuccessful(); + + $this->assertFileDoesNotExist($this->supervisorDir . '/octane.ini'); + } +} diff --git a/tests/unit/ProcessMaker/Multitenancy/SwitchTenantTest.php b/tests/unit/ProcessMaker/Multitenancy/SwitchTenantTest.php index ab017f1bf7..16f424dd3f 100644 --- a/tests/unit/ProcessMaker/Multitenancy/SwitchTenantTest.php +++ b/tests/unit/ProcessMaker/Multitenancy/SwitchTenantTest.php @@ -6,6 +6,7 @@ use Illuminate\Broadcasting\BroadcastManager; use Illuminate\Encryption\Encrypter; +use Illuminate\Support\Env; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Storage; use Laravel\Passport\ClientRepository; @@ -69,6 +70,58 @@ public function test_make_current_flushes_passport_singletons_and_auth_guards(): } } + public function test_make_current_does_not_require_missing_tenant_route_cache(): void + { + $app = app(); + // Simulate landlord route cache already evaluated during boot. + $app->instance('routes.cached', true); + + $tenant = $this->fakeTenant(); + $tenantRouteCache = base_path('storage/tenant_' . $tenant->id . '/routes-v7.php'); + $this->assertFileDoesNotExist($tenantRouteCache); + + $switch = new SwitchTenant(); + + try { + $switch->makeCurrent($tenant); + + $this->assertSame($tenantRouteCache, $app->getCachedRoutesPath()); + $this->assertFalse($app->routesAreCached()); + } finally { + $switch->forgetCurrent(); + Env::getRepository()->clear('APP_ROUTES_CACHE'); + $app->forgetInstance('routes.cached'); + } + } + + public function test_make_current_invalidates_routes_cached_when_not_running_in_console(): void + { + $app = app(); + $app->instance('routes.cached', true); + + // Mirror APP_RUNNING_IN_CONSOLE=false: shouldReinitializeRouter() is false, + // but the stale landlord routes.cached binding must still be cleared. + $property = (new ReflectionObject($app))->getProperty('isRunningInConsole'); + $previousRunningInConsole = $property->getValue($app); + $property->setValue($app, false); + + $tenant = $this->fakeTenant(); + $this->assertFileDoesNotExist(base_path('storage/tenant_' . $tenant->id . '/routes-v7.php')); + + $switch = new SwitchTenant(); + + try { + $switch->makeCurrent($tenant); + + $this->assertFalse($app->routesAreCached()); + } finally { + $switch->forgetCurrent(); + Env::getRepository()->clear('APP_ROUTES_CACHE'); + $app->forgetInstance('routes.cached'); + $property->setValue($app, $previousRunningInConsole); + } + } + public function test_make_current_flushes_cached_filesystem_disks_to_tenant_root(): void { // Warm the landlord disk the way a Horizon worker might before the first tenant job. diff --git a/tests/unit/ProcessMaker/Nayra/Services/FixBpmnSchemaServiceTest.php b/tests/unit/ProcessMaker/Nayra/Services/FixBpmnSchemaServiceTest.php index 2b3ec5adaf..c334cf5f30 100644 --- a/tests/unit/ProcessMaker/Nayra/Services/FixBpmnSchemaServiceTest.php +++ b/tests/unit/ProcessMaker/Nayra/Services/FixBpmnSchemaServiceTest.php @@ -22,7 +22,7 @@ public function testExceptionInIncompleteProcess() { $bpmn = file_get_contents( __DIR__ . - "/../../../../Fixtures/process_data_input_without_targetref.bpmn" + '/../../../../Fixtures/process_data_input_without_targetref.bpmn' ); $document = new BpmnDocument(); @@ -30,7 +30,7 @@ public function testExceptionInIncompleteProcess() $this->expectException(Exception::class); $validation = $document->validateBPMNSchema( - public_path("definitions/ProcessMaker.xsd") + public_path('definitions/ProcessMaker.xsd') ); } @@ -43,7 +43,7 @@ public function testFixIncompleteProcess() { $bpmn = file_get_contents( __DIR__ . - "/../../../../Fixtures/process_data_input_without_targetref.bpmn" + '/../../../../Fixtures/process_data_input_without_targetref.bpmn' ); $fixBpmnSchemaService = app(FixBpmnSchemaService::class); @@ -52,7 +52,7 @@ public function testFixIncompleteProcess() $document = new BpmnDocument(); $document->loadXML($bpmn); $validation = $document->validateBPMNSchema( - public_path("definitions/ProcessMaker.xsd") + public_path('definitions/ProcessMaker.xsd') ); $this->assertTrue($validation); @@ -67,7 +67,7 @@ public function testFixPm4Process() { $bpmn = file_get_contents( __DIR__ . - "/../../../../Fixtures/process_data_input_generated_in_pm4.bpmn" + '/../../../../Fixtures/process_data_input_generated_in_pm4.bpmn' ); $fixBpmnSchemaService = app(FixBpmnSchemaService::class); @@ -76,7 +76,7 @@ public function testFixPm4Process() $document = new BpmnDocument(); $document->loadXML($bpmn); $validation = $document->validateBPMNSchema( - public_path("definitions/ProcessMaker.xsd") + public_path('definitions/ProcessMaker.xsd') ); $this->assertTrue($validation); diff --git a/tests/unit/ProcessMaker/Providers/PluginServiceProviderTest.php b/tests/unit/ProcessMaker/Providers/PluginServiceProviderTest.php new file mode 100644 index 0000000000..9b5f22a618 --- /dev/null +++ b/tests/unit/ProcessMaker/Providers/PluginServiceProviderTest.php @@ -0,0 +1,42 @@ + [ + 'laravel' => [ + 'providers' => [ + 'ProcessMaker\\Package\\Missing\\PackageServiceProvider', + ], + ], + ], + ])); + + try { + $provider = new PluginServiceProvider(app()); + $method = new ReflectionMethod($provider, 'loadPlugin'); + $method->invoke($provider, $pluginPath); + + $this->assertNull(app()->getProvider('ProcessMaker\\Package\\Missing\\PackageServiceProvider')); + Log::shouldHaveReceived('warning') + ->once() + ->withArgs(fn (string $message) => str_contains($message, 'dependencies are not installed')); + } finally { + @unlink($pluginPath . '/composer.json'); + @rmdir($pluginPath); + } + } +} diff --git a/tests/unit/ProcessMaker/ScriptRunners/SmartExtractEnvironmentVariablesTest.php b/tests/unit/ProcessMaker/ScriptRunners/SmartExtractEnvironmentVariablesTest.php index 1349a02ee4..03e84a2416 100644 --- a/tests/unit/ProcessMaker/ScriptRunners/SmartExtractEnvironmentVariablesTest.php +++ b/tests/unit/ProcessMaker/ScriptRunners/SmartExtractEnvironmentVariablesTest.php @@ -22,7 +22,7 @@ public function test_local_runner_preserves_database_api_host_without_duplicates { $this->createApiHost(); $executor = ScriptExecutor::factory()->create(['language' => 'php']); - $runner = new class ($executor) extends Base { + $runner = new class($executor) extends Base { public function config($code, array $dockerConfig) { return $dockerConfig; @@ -66,7 +66,7 @@ public function test_both_runners_propagate_the_legacy_api_host_fallback(): void config(['smart-extract.api_host' => 'https://legacy.example.com']); $executor = ScriptExecutor::factory()->create(['language' => 'php']); - $localRunner = new class ($executor) extends Base { + $localRunner = new class($executor) extends Base { public function config($code, array $dockerConfig) { return $dockerConfig; @@ -106,7 +106,7 @@ public function test_existing_empty_database_api_host_suppresses_fallback_in_bot ]); $executor = ScriptExecutor::factory()->create(['language' => 'php']); - $localRunner = new class ($executor) extends Base { + $localRunner = new class($executor) extends Base { public function config($code, array $dockerConfig) { return $dockerConfig; diff --git a/tests/unit/ProcessMaker/Services/ConditionalRedirectServiceTest.php b/tests/unit/ProcessMaker/Services/ConditionalRedirectServiceTest.php index ae5eac6cd9..5c2a04c9ee 100644 --- a/tests/unit/ProcessMaker/Services/ConditionalRedirectServiceTest.php +++ b/tests/unit/ProcessMaker/Services/ConditionalRedirectServiceTest.php @@ -3,9 +3,9 @@ namespace Tests\Unit\ProcessMaker\Services; use InvalidArgumentException; +use ProcessMaker\Models\Process; use ProcessMaker\Models\ProcessRequest; use ProcessMaker\Models\ProcessRequestToken; -use ProcessMaker\Models\Process; use ProcessMaker\Models\User; use ProcessMaker\Services\ConditionalRedirectService; use Tests\TestCase; @@ -29,13 +29,13 @@ public function testResolveWithBasicConditions() [ 'condition' => 'amount > 1000', 'type' => 'externalURL', - 'value' => 'https://example.com/approval' + 'value' => 'https://example.com/approval', ], [ 'condition' => 'amount <= 1000', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; $data = ['amount' => 1500, 'status' => 'pending']; @@ -57,13 +57,13 @@ public function testResolveWithSecondConditionMatching() [ 'condition' => 'amount > 1000', 'type' => 'externalURL', - 'value' => 'https://example.com/approval' + 'value' => 'https://example.com/approval', ], [ 'condition' => 'amount <= 1000', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; $data = ['amount' => 500, 'status' => 'pending']; @@ -85,13 +85,13 @@ public function testResolveWithNoConditionsMatching() [ 'condition' => 'amount > 1000', 'type' => 'externalURL', - 'value' => 'https://example.com/approval' + 'value' => 'https://example.com/approval', ], [ 'condition' => 'status == "urgent"', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; $data = ['amount' => 500, 'status' => 'pending']; @@ -110,13 +110,13 @@ public function testResolveWithStringConditions() [ 'condition' => 'status == "urgent"', 'type' => 'externalURL', - 'value' => 'https://example.com/urgent' + 'value' => 'https://example.com/urgent', ], [ 'condition' => 'status == "normal"', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; $data = ['status' => 'urgent', 'priority' => 'high']; @@ -137,13 +137,13 @@ public function testResolveWithBooleanConditions() [ 'condition' => 'isApproved == true', 'type' => 'homepageDashboard', - 'value' => null + 'value' => null, ], [ 'condition' => 'isApproved == false', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; $data = ['isApproved' => true, 'user' => 'john']; @@ -164,13 +164,13 @@ public function testResolveWithComplexConditions() [ 'condition' => 'amount > 1000 and status == "pending"', 'type' => 'externalURL', - 'value' => 'https://example.com/approval' + 'value' => 'https://example.com/approval', ], [ 'condition' => 'amount <= 1000 or status == "urgent"', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; $data = ['amount' => 1500, 'status' => 'pending']; @@ -206,8 +206,8 @@ public function testResolveWithMissingConditionKey() $conditionalRedirect = [ [ 'type' => 'externalURL', - 'value' => 'https://example.com/approval' - ] + 'value' => 'https://example.com/approval', + ], ]; $data = ['amount' => 1500]; @@ -227,8 +227,8 @@ public function testResolveWithNullCondition() [ 'condition' => null, 'type' => 'externalURL', - 'value' => 'https://example.com/approval' - ] + 'value' => 'https://example.com/approval', + ], ]; $data = ['amount' => 1500]; @@ -245,8 +245,8 @@ public function testResolveWithEmptyCondition() [ 'condition' => '', 'type' => 'externalURL', - 'value' => 'https://example.com/approval' - ] + 'value' => 'https://example.com/approval', + ], ]; $data = ['amount' => 1500]; @@ -266,21 +266,21 @@ public function testResolveWithNestedData() [ 'condition' => 'user.role == "admin"', 'type' => 'externalURL', - 'value' => 'https://example.com/admin' + 'value' => 'https://example.com/admin', ], [ 'condition' => 'user.role == "user"', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; $data = [ 'user' => [ 'role' => 'admin', - 'name' => 'John Doe' + 'name' => 'John Doe', ], - 'status' => 'active' + 'status' => 'active', ]; $result = $this->service->resolve($conditionalRedirect, $data); @@ -300,7 +300,7 @@ public function testResolveWithTokenData() // Create a process $process = Process::factory()->create([ - 'user_id' => $user->id + 'user_id' => $user->id, ]); // Create a process request with test data @@ -310,8 +310,8 @@ public function testResolveWithTokenData() 'data' => [ 'amount' => 1500, 'status' => 'pending', - 'priority' => 'high' - ] + 'priority' => 'high', + ], ]); // Create a process request token @@ -321,20 +321,20 @@ public function testResolveWithTokenData() 'element_id' => 'task_1', 'element_type' => 'task', 'element_name' => 'Review Task', - 'status' => 'ACTIVE' + 'status' => 'ACTIVE', ]); $conditionalRedirect = [ [ 'condition' => 'amount > 1000', 'type' => 'externalURL', - 'value' => 'https://example.com/approval' + 'value' => 'https://example.com/approval', ], [ 'condition' => 'amount <= 1000', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; // Get the data from the process request and test with resolve() method @@ -356,7 +356,7 @@ public function testResolveWithNoMatchingConditionsUsingTokenData() // Create a process $process = Process::factory()->create([ - 'user_id' => $user->id + 'user_id' => $user->id, ]); // Create a process request with data that won't match any conditions @@ -365,8 +365,8 @@ public function testResolveWithNoMatchingConditionsUsingTokenData() 'user_id' => $user->id, 'data' => [ 'amount' => 500, - 'status' => 'pending' - ] + 'status' => 'pending', + ], ]); // Create a process request token @@ -376,20 +376,20 @@ public function testResolveWithNoMatchingConditionsUsingTokenData() 'element_id' => 'task_1', 'element_type' => 'task', 'element_name' => 'Review Task', - 'status' => 'ACTIVE' + 'status' => 'ACTIVE', ]); $conditionalRedirect = [ [ 'condition' => 'amount > 1000', 'type' => 'externalURL', - 'value' => 'https://example.com/approval' + 'value' => 'https://example.com/approval', ], [ 'condition' => 'status == "urgent"', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; // Get the data from the process request and test with resolve() method @@ -409,7 +409,7 @@ public function testResolveWithMultiInstanceTaskData() // Create a process $process = Process::factory()->create([ - 'user_id' => $user->id + 'user_id' => $user->id, ]); // Create a process request with multi-instance data @@ -418,8 +418,8 @@ public function testResolveWithMultiInstanceTaskData() 'user_id' => $user->id, 'data' => [ 'items' => ['item1', 'item2', 'item3'], - 'status' => 'processing' - ] + 'status' => 'processing', + ], ]); // Create a process request token with multi-instance properties @@ -433,22 +433,22 @@ public function testResolveWithMultiInstanceTaskData() 'token_properties' => [ 'data' => [ 'currentItem' => 'item1', - 'loopCounter' => 0 - ] - ] + 'loopCounter' => 0, + ], + ], ]); $conditionalRedirect = [ [ 'condition' => 'loopCounter == 0', 'type' => 'externalURL', - 'value' => 'https://example.com/first-item' + 'value' => 'https://example.com/first-item', ], [ 'condition' => 'loopCounter > 0', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; // For multi-instance, we need to combine the process request data with token properties @@ -469,13 +469,13 @@ public function testResolveWithNumericConditions() [ 'condition' => 'count >= 5', 'type' => 'externalURL', - 'value' => 'https://example.com/bulk' + 'value' => 'https://example.com/bulk', ], [ 'condition' => 'count < 5', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; $data = ['count' => 7, 'type' => 'batch']; @@ -496,13 +496,13 @@ public function testResolveWithDateConditions() [ 'condition' => 'dueDate < date("2024-01-01")', 'type' => 'externalURL', - 'value' => 'https://example.com/overdue' + 'value' => 'https://example.com/overdue', ], [ 'condition' => 'dueDate >= date("2024-01-01")', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; $data = ['dueDate' => '2023-12-15', 'status' => 'pending']; @@ -523,13 +523,13 @@ public function testResolveWithMultipleConditionsInOneItem() [ 'condition' => 'amount > 1000 and status == "pending" and priority == "high"', 'type' => 'externalURL', - 'value' => 'https://example.com/urgent-approval' + 'value' => 'https://example.com/urgent-approval', ], [ 'condition' => 'amount <= 1000 or status = "completed"', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; $data = ['amount' => 1500, 'status' => 'pending', 'priority' => 'high']; @@ -550,13 +550,13 @@ public function testResolveWithNullDataValues() [ 'condition' => 'value == null', 'type' => 'externalURL', - 'value' => 'https://example.com/null-value' + 'value' => 'https://example.com/null-value', ], [ 'condition' => 'value != null', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; $data = ['value' => null, 'status' => 'pending']; @@ -577,13 +577,13 @@ public function testResolveWithArrayDataValues() [ 'condition' => '"urgent" in items', 'type' => 'externalURL', - 'value' => 'https://example.com/urgent-items' + 'value' => 'https://example.com/urgent-items', ], [ 'condition' => '"normal" in items', 'type' => 'taskList', - 'value' => null - ] + 'value' => null, + ], ]; $data = ['items' => ['urgent', 'normal', 'low'], 'status' => 'processing']; diff --git a/tests/unit/Providers/MixTenantPluginVendorTest.php b/tests/unit/Providers/MixTenantPluginVendorTest.php new file mode 100644 index 0000000000..90d18e5a5f --- /dev/null +++ b/tests/unit/Providers/MixTenantPluginVendorTest.php @@ -0,0 +1,50 @@ +deleteTree($tenantDir); + + config(['app.multitenancy' => true, 'plugin_manager.tenant_plugin_assets_enabled' => true]); + $this->app->instance('currentTenant', (object) ['id' => self::TENANT_ID]); + + $root = PluginVendorAssets::tenantPackageRoot(self::TENANT_ID, 'mix-test-pkg'); + mkdir($root . '/js', 0755, true); + file_put_contents($root . '/mix-manifest.json', json_encode([ + '/js/widget.js' => '/js/widget.js?id=tenant-hash', + ])); + + $url = (string) app(Mix::class)('js/widget.js', 'vendor/processmaker/packages/mix-test-pkg'); + + $this->assertStringContainsString('/storage/vendor/processmaker/packages/mix-test-pkg/js/widget.js?id=tenant-hash', $url); + $this->assertStringNotContainsString('/storage/tenant_', $url); + + $this->app->offsetUnset('currentTenant'); + $this->deleteTree($tenantDir); + } + + private function deleteTree(string $dir): void + { + if (!is_dir($dir)) { + return; + } + foreach (scandir($dir) ?: [] as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } + $path = $dir . DIRECTORY_SEPARATOR . $entry; + is_dir($path) ? $this->deleteTree($path) : unlink($path); + } + rmdir($dir); + } +} diff --git a/tests/unit/ScriptMicroserviceServiceTest.php b/tests/unit/ScriptMicroserviceServiceTest.php index b2850ee79e..620f64042d 100644 --- a/tests/unit/ScriptMicroserviceServiceTest.php +++ b/tests/unit/ScriptMicroserviceServiceTest.php @@ -70,7 +70,7 @@ public function testHandlePreviewError() 'file' => 'Test error file', 'line' => 'Test line number', 'trace' => 'Test trace', - ] + ], ]); $this->service->handle($request); diff --git a/tests/unit/ScriptRunners/InProcessPhpRunnerTest.php b/tests/unit/ScriptRunners/InProcessPhpRunnerTest.php new file mode 100644 index 0000000000..430ab647eb --- /dev/null +++ b/tests/unit/ScriptRunners/InProcessPhpRunnerTest.php @@ -0,0 +1,85 @@ +withPersonalAccessClient(); + } + + public function testRunsPhpScriptAndReturnsArray(): void + { + $runner = new InProcessPhpRunner(); + $user = User::factory()->create(); + + $output = $runner->run( + ' $data["ping"], "cfg" => $config["mode"] ?? null];', + ['ping' => 'hello'], + ['mode' => 'test'], + 30, + $user + ); + + $this->assertSame('hello', $output['pong']); + $this->assertSame('test', $output['cfg']); + } + + public function testThrowsOnInvalidPhp(): void + { + $this->expectException(ScriptException::class); + + $runner = new InProcessPhpRunner(); + $runner->run( + 'create() + ); + } + + public function testRespectsTimeout(): void + { + $this->expectException(ScriptTimeoutException::class); + + $runner = new InProcessPhpRunner(); + $runner->run( + ' true];', + [], + [], + 1, + User::factory()->create() + ); + } + + public function testExposesApiHostAndTokenViaGetenv(): void + { + config(['app.docker_host_url' => 'https://pm.example.test']); + + $runner = new InProcessPhpRunner(); + $output = $runner->run( + ' getenv("API_HOST"), + "has_token" => is_string(getenv("API_TOKEN")) && getenv("API_TOKEN") !== "", + "app_url" => getenv("APP_URL"), + ];', + [], + [], + 30, + User::factory()->create() + ); + + $this->assertSame('https://pm.example.test/api/1.0', $output['host']); + $this->assertTrue($output['has_token']); + $this->assertSame('https://pm.example.test', $output['app_url']); + } +} diff --git a/tests/unit/ScriptRunners/ScriptRunnerInProcessTest.php b/tests/unit/ScriptRunners/ScriptRunnerInProcessTest.php new file mode 100644 index 0000000000..344ca83cec --- /dev/null +++ b/tests/unit/ScriptRunners/ScriptRunnerInProcessTest.php @@ -0,0 +1,103 @@ +withPersonalAccessClient(); + config([ + 'core-service-task.enabled' => true, + 'core-service-task.execution' => 'modules', + 'core-service-task.modules_enabled' => true, + // Ensure local runner path is available for non-in-process fallback construction + 'script-runner-microservice.enabled' => false, + 'script-runners.php.runner' => 'MockRunner', + ]); + } + + public function testRunsAllowInProcessScriptViaScriptRuntime(): void + { + $user = User::factory()->create(); + $script = Script::factory()->create([ + 'language' => 'php', + 'code' => ' "docker"];', + 'run_as_user_id' => $user->id, + 'allow_in_process' => true, + 'execution_mode' => Script::EXECUTION_MODE_MODULES, + 'timeout' => 30, + ]); + + $runner = new ScriptRunner($script); + $response = $runner->run( + ' "in-process", "ping" => $data["ping"]];', + ['ping' => '1'], + [], + 30, + $user, + 1, + [] + ); + + $this->assertSame('in-process', $response['output']['via']); + $this->assertSame('1', $response['output']['ping']); + } + + public function testSkipsInProcessWhenFlagDisabled(): void + { + config(['core-service-task.enabled' => false]); + + $user = User::factory()->create(); + $script = Script::factory()->create([ + 'language' => 'php', + 'code' => ' "stored"];', + 'run_as_user_id' => $user->id, + 'allow_in_process' => true, + ]); + + $runner = new ScriptRunner($script); + // MockRunner evals the passed $code + $response = $runner->run( + ' "mock"];', + [], + [], + 30, + $user, + 1, + [] + ); + + $this->assertSame('mock', $response['output']['via']); + } + + public function testSkipsInProcessWhenScriptNotAllowlisted(): void + { + $user = User::factory()->create(); + $script = Script::factory()->create([ + 'language' => 'php', + 'code' => ' "stored"];', + 'run_as_user_id' => $user->id, + 'allow_in_process' => false, + ]); + + $runner = new ScriptRunner($script); + $response = $runner->run( + ' "mock"];', + [], + [], + 30, + $user, + 1, + [] + ); + + $this->assertSame('mock', $response['output']['via']); + } +} diff --git a/tests/unit/ScriptRuntime/ScriptRuntimeTest.php b/tests/unit/ScriptRuntime/ScriptRuntimeTest.php new file mode 100644 index 0000000000..b02507efe5 --- /dev/null +++ b/tests/unit/ScriptRuntime/ScriptRuntimeTest.php @@ -0,0 +1,233 @@ +withPersonalAccessClient(); + // Fresh registry per test (clear Facade cache so bindings apply) + ScriptRuntime::clearResolvedInstances(); + $registry = new ScriptModuleRegistry(); + $runtime = new \ProcessMaker\ScriptRuntime\ScriptRuntime($registry); + $this->app->instance(ScriptModuleRegistry::class, $registry); + $this->app->instance(\ProcessMaker\ScriptRuntime\ScriptRuntime::class, $runtime); + $this->app->instance('script.runtime', $runtime); + } + + public function testRegisterModuleAndCatalog(): void + { + ScriptRuntime::registerModule(FakeEchoModule::class); + + $this->assertTrue(ScriptRuntime::registry()->has('echo')); + $catalog = ScriptRuntime::catalog(); + $this->assertSame('echo', $catalog[0]['key']); + $this->assertArrayHasKey('ping', $catalog[0]['methods']); + } + + public function testRunScriptWithModuleVariable(): void + { + ScriptRuntime::registerModule(FakeEchoModule::class); + $user = User::factory()->create(); + + $output = ScriptRuntime::run( + ' $echo->ping($data["ping"]), "keys" => array_keys($modules)];', + new ScriptExecutionContext( + data: ['ping' => 'hello'], + config: [], + user: $user, + source: 'preview', + ) + ); + + $this->assertSame('hello', $output['pong']); + $this->assertContains('echo', $output['keys']); + } + + public function testRunScriptWithLegacyResultVariable(): void + { + $output = ScriptRuntime::run( + ' $data["ping"]];', + new ScriptExecutionContext( + data: ['ping' => 'hello'], + config: [], + user: null, + source: 'preview', + ) + ); + + $this->assertSame(['pong' => 'hello'], $output); + } + + public function testLegacyResultIgnoresNestedReturns(): void + { + $output = ScriptRuntime::run( + <<<'PHP' + helper()]; +PHP, + new ScriptExecutionContext( + data: [], + config: [], + user: null, + source: 'preview', + ) + ); + + $this->assertSame(['ok' => true], $output); + } + + public function testLegacyResultIgnoresReturnsInsideInterpolatedStrings(): void + { + $output = ScriptRuntime::run( + <<<'PHP' + $helper('ok')]; +PHP, + new ScriptExecutionContext( + data: [], + config: [], + user: null, + source: 'preview', + ) + ); + + $this->assertSame(['value' => 'value: ok'], $output); + } + + public function testRunScriptWithExplicitScalarReturn(): void + { + $output = ScriptRuntime::run( + 'assertSame(1, $output); + } + + public function testRunScriptWithExplicitNullReturn(): void + { + $output = ScriptRuntime::run( + 'assertNull($output); + } + + public function testRejectsReservedModuleKey(): void + { + $this->expectException(\InvalidArgumentException::class); + ScriptRuntime::registerModule(FakeReservedModule::class); + } + + public function testNormalizeOutput(): void + { + $this->assertSame([], ScriptRuntime::normalizeOutput(null)); + $this->assertSame(['response' => 1], ScriptRuntime::normalizeOutput(1)); + $this->assertSame(['a' => 1], ScriptRuntime::normalizeOutput(['a' => 1])); + } + + public function testExposesApiHostAndTokenViaGetenv(): void + { + config(['app.docker_host_url' => 'https://pm.example.test']); + $user = User::factory()->create(); + + $output = ScriptRuntime::run( + ' getenv("API_HOST"), + "has_token" => is_string(getenv("API_TOKEN")) && getenv("API_TOKEN") !== "", + "app_url" => getenv("APP_URL"), + ];', + new ScriptExecutionContext( + data: [], + config: [], + user: $user, + source: 'preview', + ) + ); + + $this->assertSame('https://pm.example.test/api/1.0', $output['host']); + $this->assertTrue($output['has_token']); + $this->assertSame('https://pm.example.test', $output['app_url']); + // Token must not leak into the parent process after the run + $this->assertFalse(getenv('API_TOKEN')); + } +} + +class FakeEchoModule implements ScriptModuleInterface +{ + public static function key(): string + { + return 'echo'; + } + + public static function label(): string + { + return 'Echo'; + } + + public static function catalog(): array + { + return ['ping' => ['params' => ['value' => 'string']]]; + } + + public function boot(ScriptExecutionContext $context): void + { + } + + public function ping(string $value): string + { + return $value; + } +} + +class FakeReservedModule implements ScriptModuleInterface +{ + public static function key(): string + { + return 'data'; + } + + public static function label(): string + { + return 'Reserved'; + } + + public static function catalog(): array + { + return []; + } + + public function boot(ScriptExecutionContext $context): void + { + } +} diff --git a/tests/unit/ServiceTaskImplementations/CoreServiceTaskModulesTest.php b/tests/unit/ServiceTaskImplementations/CoreServiceTaskModulesTest.php new file mode 100644 index 0000000000..cbbf2b391d --- /dev/null +++ b/tests/unit/ServiceTaskImplementations/CoreServiceTaskModulesTest.php @@ -0,0 +1,85 @@ +withPersonalAccessClient(); + config([ + 'core-service-task.enabled' => true, + 'core-service-task.execution' => 'modules', + 'core-service-task.modules_enabled' => true, + ]); + + ScriptRuntime::clearResolvedInstances(); + $registry = new ScriptModuleRegistry(); + $runtime = new \ProcessMaker\ScriptRuntime\ScriptRuntime($registry); + $this->app->instance(ScriptModuleRegistry::class, $registry); + $this->app->instance(\ProcessMaker\ScriptRuntime\ScriptRuntime::class, $runtime); + $this->app->instance('script.runtime', $runtime); + + ScriptRuntime::registerModule(CoreTaskFakeModule::class); + } + + public function testRunsWithRegisteredModule(): void + { + $user = User::factory()->create(); + $script = Script::factory()->create([ + 'language' => 'php', + 'code' => ' $demo->value()];', + 'run_as_user_id' => $user->id, + 'allow_in_process' => true, + 'execution_mode' => Script::EXECUTION_MODE_MODULES, + 'timeout' => 30, + ]); + + $output = (new CoreServiceTask())->run( + [], + ['script_id' => $script->id], + 'tok', + 30 + ); + + $this->assertSame('ok', $output['out']); + } +} + +class CoreTaskFakeModule implements ScriptModuleInterface +{ + public static function key(): string + { + return 'demo'; + } + + public static function label(): string + { + return 'Demo'; + } + + public static function catalog(): array + { + return ['value' => []]; + } + + public function boot(ScriptExecutionContext $context): void + { + } + + public function value(): string + { + return 'ok'; + } +} diff --git a/tests/unit/ServiceTaskImplementations/CoreServiceTaskTest.php b/tests/unit/ServiceTaskImplementations/CoreServiceTaskTest.php new file mode 100644 index 0000000000..36b688f5c2 --- /dev/null +++ b/tests/unit/ServiceTaskImplementations/CoreServiceTaskTest.php @@ -0,0 +1,144 @@ +withPersonalAccessClient(); + config(['core-service-task.enabled' => true]); + } + + public function testIsRegistered(): void + { + $this->assertTrue( + WorkflowManager::existsServiceImplementation(CoreServiceTask::IMPLEMENTATION) + ); + } + + public function testRunsAllowlistedPhpScript(): void + { + $user = User::factory()->create(); + $script = Script::factory()->create([ + 'language' => 'php', + 'code' => ' $data["ping"]];', + 'run_as_user_id' => $user->id, + 'allow_in_process' => true, + 'timeout' => 30, + ]); + + $task = new CoreServiceTask(); + $output = $task->run( + ['ping' => '1'], + ['script_id' => $script->id], + 'token-1', + 30 + ); + + $this->assertSame('1', $output['pong']); + } + + public function testFailsWhenDisabled(): void + { + config(['core-service-task.enabled' => false]); + + $this->expectException(ConfigurationException::class); + $this->expectExceptionMessage('Core Service Task is disabled'); + + (new CoreServiceTask())->run([], ['script_id' => 1]); + } + + public function testFailsWithoutScriptId(): void + { + $this->expectException(ConfigurationException::class); + $this->expectExceptionMessage('script_id'); + + (new CoreServiceTask())->run([], []); + } + + public function testFailsWhenScriptNotAllowlisted(): void + { + $script = Script::factory()->create([ + 'language' => 'php', + 'code' => ' false, + ]); + + $this->expectException(ConfigurationException::class); + $this->expectExceptionMessage('not allowed for in-process'); + + (new CoreServiceTask())->run([], ['script_id' => $script->id]); + } + + public function testFailsForNonPhpScript(): void + { + $script = Script::factory()->create([ + 'language' => 'php', + 'code' => ' true, + ]); + + // Bypass model events to simulate a non-PHP allowlisted row + Script::whereKey($script->id)->update([ + 'language' => 'javascript', + 'allow_in_process' => true, + ]); + + $this->expectException(ConfigurationException::class); + $this->expectExceptionMessage('only supports PHP'); + + (new CoreServiceTask())->run([], ['script_id' => $script->id]); + } + + public function testRejectsAllowInProcessForNonPhpOnSave(): void + { + $script = Script::factory()->create([ + 'language' => 'php', + 'code' => ' false, + ]); + + $this->expectException(\Illuminate\Validation\ValidationException::class); + + $script->language = 'javascript'; + $script->allow_in_process = true; + $script->save(); + } + + public function testCapsTimeoutToMax(): void + { + config([ + 'core-service-task.max_timeout' => 2, + 'core-service-task.default_timeout' => 60, + // Timeout hard-kill is enforced by the bare PHP subprocess runner + 'core-service-task.execution' => 'bare', + ]); + + $user = User::factory()->create(); + $script = Script::factory()->create([ + 'language' => 'php', + 'code' => ' true];', + 'run_as_user_id' => $user->id, + 'allow_in_process' => true, + 'timeout' => 60, + ]); + + $this->expectException(\ProcessMaker\Exception\ScriptTimeoutException::class); + + (new CoreServiceTask())->run( + [], + ['script_id' => $script->id], + '', + 999 + ); + } +} diff --git a/tests/unit/Services/PluginRuntimeReloadLocalRecycleTest.php b/tests/unit/Services/PluginRuntimeReloadLocalRecycleTest.php new file mode 100644 index 0000000000..ad44f9aa6c --- /dev/null +++ b/tests/unit/Services/PluginRuntimeReloadLocalRecycleTest.php @@ -0,0 +1,58 @@ + false]); + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + Artisan::shouldReceive('call') + ->once() + ->with('horizon:terminate', ['--no-interaction' => true]) + ->andReturn(0); + + $this->assertTrue((new PluginRuntimeReload())->recycleLocalRuntime()); + + Process::assertRan(fn ($process) => is_array($process->command) + && $process->command === ['supervisorctl', 'restart', 'octane:*']); + } + + public function testRecycleLocalRuntimeInMultitenantModeUsesTenantProgram(): void + { + config(['app.multitenancy' => true]); + app()->instance('currentTenant', new class { + public function getKey(): int + { + return 5; + } + }); + Process::fake([ + '*' => Process::result('', exitCode: 0), + ]); + Artisan::shouldReceive('call') + ->once() + ->with('horizon:terminate', ['--no-interaction' => true]) + ->andReturn(0); + + $this->assertTrue((new PluginRuntimeReload())->recycleLocalRuntime()); + + Process::assertRan(fn ($process) => is_array($process->command) + && $process->command === ['supervisorctl', 'restart', 'octane-tenant-5:*']); + } + + public function testRecycleLocalRuntimeFailsWithoutTenantInMultitenantMode(): void + { + config(['app.multitenancy' => true]); + + $this->assertFalse((new PluginRuntimeReload())->recycleLocalRuntime()); + } +} \ No newline at end of file diff --git a/tests/unit/Services/ScriptExecutionModeResolverTest.php b/tests/unit/Services/ScriptExecutionModeResolverTest.php new file mode 100644 index 0000000000..24f546e4d7 --- /dev/null +++ b/tests/unit/Services/ScriptExecutionModeResolverTest.php @@ -0,0 +1,80 @@ +create(); + + $this->assertSame( + Script::EXECUTION_MODE_BARE, + $script->fresh()->execution_mode + ); + } + + public function testDefaultsToBare(): void + { + config(['core-service-task.modules_enabled' => true]); + + $script = new Script([ + 'allow_in_process' => true, + 'execution_mode' => Script::EXECUTION_MODE_BARE, + ]); + + $this->assertSame( + Script::EXECUTION_MODE_BARE, + (new ScriptExecutionModeResolver())->resolve($script) + ); + } + + public function testAllowsModulesForExplicitlyConfiguredScript(): void + { + config(['core-service-task.modules_enabled' => true]); + + $script = new Script([ + 'allow_in_process' => true, + 'execution_mode' => Script::EXECUTION_MODE_MODULES, + ]); + + $this->assertSame( + Script::EXECUTION_MODE_MODULES, + (new ScriptExecutionModeResolver())->resolve($script) + ); + } + + public function testFallsBackToBareWhenModulesAreDisabled(): void + { + config(['core-service-task.modules_enabled' => false]); + + $script = new Script([ + 'allow_in_process' => true, + 'execution_mode' => Script::EXECUTION_MODE_MODULES, + ]); + + $this->assertSame( + Script::EXECUTION_MODE_BARE, + (new ScriptExecutionModeResolver())->resolve($script) + ); + } + + public function testDisallowsModulesForScriptsNotAllowedInProcess(): void + { + config(['core-service-task.modules_enabled' => true]); + + $script = new Script([ + 'allow_in_process' => false, + 'execution_mode' => Script::EXECUTION_MODE_MODULES, + ]); + + $this->assertSame( + Script::EXECUTION_MODE_BARE, + (new ScriptExecutionModeResolver())->resolve($script) + ); + } +} diff --git a/tests/unit/Support/PluginVendorAssetsTest.php b/tests/unit/Support/PluginVendorAssetsTest.php new file mode 100644 index 0000000000..e6ecd0e096 --- /dev/null +++ b/tests/unit/Support/PluginVendorAssetsTest.php @@ -0,0 +1,66 @@ +deleteTree($tenantDir); + + $this->assertSame( + base_path('storage/tenant_987651/app/public/vendor/processmaker/packages/package-plg'), + PluginVendorAssets::tenantPackageRoot(self::TENANT_ID, 'package-plg') + ); + $this->assertSame( + '/storage/vendor/processmaker/packages/package-plg/js/a.js?id=1', + PluginVendorAssets::webPath('package-plg', '/js/a.js?id=1') + ); + $this->assertSame('package-plg', PluginVendorAssets::parsePackageFromManifestDirectory('/vendor/processmaker/packages/package-plg/')); + $this->assertNull(PluginVendorAssets::parsePackageFromManifestDirectory('vendor/other')); + + config(['app.multitenancy' => true, 'plugin_manager.tenant_plugin_assets_enabled' => true]); + $this->app->instance('currentTenant', (object) ['id' => self::TENANT_ID]); + + $this->assertSame( + base_path('storage/tenant_987651/app/public/vendor/processmaker/packages/package-plg/js/a.js'), + PluginVendorAssets::filesystemPathForStorageUrl('/storage/vendor/processmaker/packages/package-plg/js/a.js?id=1') + ); + $this->assertNull(PluginVendorAssets::filesystemPathForStorageUrl('/storage/other/file.js')); + + $this->assertFalse(PluginVendorAssets::publishedVendorPackageIsAvailable('vendor/processmaker/packages/avail-' . self::TENANT_ID)); + + $root = PluginVendorAssets::tenantPackageRoot(self::TENANT_ID, 'avail-pkg'); + mkdir($root, 0755, true); + file_put_contents($root . '/mix-manifest.json', '{}'); + $this->assertTrue(PluginVendorAssets::publishedVendorPackageIsAvailable('vendor/processmaker/packages/avail-pkg')); + + config(['plugin_manager.tenant_plugin_assets_enabled' => false]); + $this->assertFalse(PluginVendorAssets::isEnabled()); + $this->assertFalse(PluginVendorAssets::publishedVendorPackageIsAvailable('vendor/processmaker/packages/avail-pkg')); + + $this->app->offsetUnset('currentTenant'); + $this->deleteTree($tenantDir); + } + + private function deleteTree(string $dir): void + { + if (!is_dir($dir)) { + return; + } + foreach (scandir($dir) ?: [] as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } + $path = $dir . DIRECTORY_SEPARATOR . $entry; + is_dir($path) ? $this->deleteTree($path) : unlink($path); + } + rmdir($dir); + } +} diff --git a/tests/unit/Traits/PluginServiceProviderTraitModelerTest.php b/tests/unit/Traits/PluginServiceProviderTraitModelerTest.php new file mode 100644 index 0000000000..40ddc802a9 --- /dev/null +++ b/tests/unit/Traits/PluginServiceProviderTraitModelerTest.php @@ -0,0 +1,75 @@ + true]); + config(['plugin_manager.tenant_plugin_assets_enabled' => true]); + $this->app->instance('currentTenant', (object) ['id' => 8]); + + $package = 'modeler-trait-pkg-' . uniqid(); + $tenantRoot = PluginVendorAssets::tenantPackageRoot(8, $package); + mkdir($tenantRoot . '/js', 0755, true); + file_put_contents($tenantRoot . '/mix-manifest.json', json_encode([ + '/js/modeler-schema-profile.js' => '/js/modeler-schema-profile.js?id=trait-test', + ])); + + $provider = new class(app()) extends ServiceProvider { + use PluginServiceProviderTrait; + + public function runModelerStarting(ModelerManager $manager, string $package): void + { + $this->registerModelerScript( + 'js/modeler-schema-profile.js', + 'vendor/processmaker/packages/' . $package, + ['type' => 'module'] + ); + $this->modelerStarting(new ModelerStarting($manager)); + } + }; + + $manager = new ModelerManager(); + $provider->runModelerStarting($manager, $package); + + $scripts = $manager->getScriptWithParams(); + $found = false; + foreach ($scripts as $script) { + if (str_contains($script['src'], '/storage/vendor/processmaker/packages/' . $package)) { + $found = true; + break; + } + } + $this->assertTrue($found, 'Expected tenant modeler script URL in manager registry'); + + $this->deleteDirectory($tenantRoot); + } + + private function deleteDirectory(string $dir): void + { + if (!is_dir($dir)) { + return; + } + foreach (scandir($dir) ?: [] as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } + $path = $dir . DIRECTORY_SEPARATOR . $entry; + if (is_dir($path)) { + $this->deleteDirectory($path); + } else { + unlink($path); + } + } + rmdir($dir); + } +} diff --git a/upgrades/2026_11_06_143900_add_mcp_settings_menu.php b/upgrades/2026_11_06_143900_add_mcp_settings_menu.php new file mode 100644 index 0000000000..69a0c181c3 --- /dev/null +++ b/upgrades/2026_11_06_143900_add_mcp_settings_menu.php @@ -0,0 +1,28 @@ +run(); + } + + /** + * Reverse the upgrade migration. + */ + public function down(): void + { + Setting::whereIn('key', [ + McpGuidance::SYSTEM_PROMPT_KEY, + McpGuidance::SKILLS_KEY, + ])->delete(); + } +} diff --git a/upgrades/2026_11_09_141900_change_settings_config_to_longtext.php b/upgrades/2026_11_09_141900_change_settings_config_to_longtext.php new file mode 100644 index 0000000000..20894b46be --- /dev/null +++ b/upgrades/2026_11_09_141900_change_settings_config_to_longtext.php @@ -0,0 +1,25 @@ +longText('config')->nullable()->change(); + }); + } + + public function down(): void + { + Schema::table('settings', function (Blueprint $table) { + $table->text('config')->nullable()->change(); + }); + } +} diff --git a/upgrades/2026_11_10_145700_make_oauth_clients_secret_nullable.php b/upgrades/2026_11_10_145700_make_oauth_clients_secret_nullable.php new file mode 100644 index 0000000000..1e86d3eaf3 --- /dev/null +++ b/upgrades/2026_11_10_145700_make_oauth_clients_secret_nullable.php @@ -0,0 +1,28 @@ +string('secret', 100)->nullable()->change(); + }); + } + + /** + * Reverse the upgrade migration. + */ + public function down(): void + { + Schema::table('oauth_clients', function (Blueprint $table) { + $table->string('secret', 100)->nullable(false)->change(); + }); + } +}; diff --git a/upgrades/2026_11_11_190000_remove_mcp_system_skills.php b/upgrades/2026_11_11_190000_remove_mcp_system_skills.php new file mode 100644 index 0000000000..25e26639b2 --- /dev/null +++ b/upgrades/2026_11_11_190000_remove_mcp_system_skills.php @@ -0,0 +1,67 @@ +first(); + if ($setting === null) { + return; + } + + $skills = is_array($setting->config) ? $setting->config : []; + $custom = array_values(array_filter( + $skills, + fn ($skill) => !$this->isSystemSkill($skill) + )); + + $setting->config = $custom; + $setting->helper = McpSettingsSeeder::SKILLS_HELPER; + $setting->saveOrFail(); + } + + /** + * System skills cannot be restored from this repository, so there is + * nothing to reverse. Custom skills are untouched. + */ + public function down(): void + { + // + } + + private function isSystemSkill(mixed $skill): bool + { + if (!is_array($skill)) { + return false; + } + + $id = trim((string) ($skill['id'] ?? '')); + + return !empty($skill['system']) + || str_starts_with($id, self::SYSTEM_ID_PREFIX) + || in_array($id, self::LEGACY_SYSTEM_IDS, true); + } +} diff --git a/vite.config.js b/vite.config.js index 7564fe6dc4..218e729625 100644 --- a/vite.config.js +++ b/vite.config.js @@ -206,6 +206,8 @@ export default defineConfig(({ mode }) => { "resources/js/vite/tasks/loaderTasks.js", "resources/js/vite/tasks/tasks.js", + "resources/js/admin/plugins/index.js", + "resources/js/tasks/loaderEdit.js", "resources/js/tasks/edit.js", "resources/js/tasks/loaderPreview.js",