arc-1
ARC-1 — SAP ADT MCP Server
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/arc-mcp/arc-1 with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/arc-mcp/arc-1'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/arc-mcp--arc-1)HTML
<a href="/listings/arc-mcp--arc-1"><img src="/api/listings/arc-mcp--arc-1/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
**Install as an Agent Plugin** — one portable install for the MCP server and all bundled SAP skills in GitHub Copilot, VS Code, Cursor, Codex, and other compatible clients:
copilot plugin marketplace add arc-mcp/arc-1 copilot plugin install arc-1@arc-1
Agent Plugins 1.0 does not define secret prompts, so create the ARC-1 `.env` in the installed plugin's persistent data directory before connecting to SAP. See the **[Agent Plugin guide](https://docs.arc-1-mcp.com/agent-plugin/)** for client-specific installation, safe configuration, and verification.
**Install in Claude** — pick your surface (full guide: [Install in Claude](https://docs.arc-1-mcp.com/install-in-claude/)):
- **Claude Desktop** — download the latest `arc-1-*.mcpb` from [Releases](https://github.com/arc-mcp/arc-1/releases) and double-click it (or Settings → Extensions). Claude prompts for your SAP connection. (The `.mcpb` is attached to releases automatically; if the newest one doesn't have it yet, see [Install in Claude](https://docs.arc-1-mcp.com/install-in-claude/).) - **Claude Code** — one install for the MCP server **and** all [SAP skills](https://github.com/arc-mcp/arc-1/tree/main/skills):
/plugin marketplace add arc-mcp/arc-1 /plugin install arc-1@arc-1
- **Any MCP client / manual** — run it directly:
npx arc-1@latest --url https://your-sap-host:44300 --user YOUR_USER
- **Trying it out on your laptop?** → [Quickstart](https://docs.arc-1-mcp.com/quickstart/) - **Full local dev setup (Docker, cookie extractor, client configs)?** → [Local Development](https://docs.arc-1-mcp.com/local-development/) - **Deploying for a team / BTP?** → [Deployment](https://docs.arc-1-mcp.com/deployment/)
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 26 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- {
- "$schema": "https://json.schemastore.org/claude-code-plugin-marketplace.json",
- "name": "arc-1",
- "owner": {
- "name": "Marian Zeis"
- },
- "metadata": {
- "description": "ARC-1 — SAP ABAP development tools for AI coding agents (MCP server + SAP skills)."
- },
- "plugins": [
- {
- "name": "arc-1",
- "source": "./",
- "description": "SAP ABAP development for AI coding agents: the ARC-1 MCP server (read/write/search/activate/lint/diagnose ABAP via ADT) plus best-practice skills for RAP, CDS, ABAP Unit, clean-core, and UI5 modernization. Read-only by default.",
- "author": {
- "name": "Marian Zeis"
- },
- "homepage": "https://docs.arc-1-mcp.com/",
- "repository": "https://github.com/arc-mcp/arc-1",
- "license": "MIT",
- "category": "Developer Tools",
- "keywords": ["sap", "abap", "adt", "s4hana", "btp", "rap", "cds", "fiori"],
- "tags": ["sap", "abap", "erp", "enterprise"]
- }
- ]
- }
README.md · README · 261 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.
- # ARC-1 — SAP ADT MCP Server
- **ARC-1** (pronounced _arc one_ [ɑːrk wʌn]) — Enterprise-ready MCP server for SAP ABAP systems. Secure by default, deployable to BTP or on-premise, and hardened with large unit/integration/E2E test coverage.
- ARC-1 connects AI assistants (Claude, GitHub Copilot, Copilot Studio, and any MCP client) to SAP systems via the [ADT REST API](https://help.sap.com/docs/abap-cloud/abap-development-tools-user-guide/about-abap-development-tools). It ships as an [npm package](https://www.npmjs.com/package/arc-1) and [Docker image](https://github.com/arc-mcp/arc-1/pkgs/container/arc-1).
- [](https://github.com/arc-mcp/arc-1/actions/workflows/test.yml)
- [](https://github.com/arc-mcp/arc-1/security/code-scanning)
- [](https://github.com/arc-mcp/arc-1/actions/workflows/dependency-review.yml)
- **[Full Documentation](https://docs.arc-1-mcp.com/)** | **[Quickstart](https://docs.arc-1-mcp.com/quickstart/)** | **[Security Review](https://docs.arc-1-mcp.com/security/)** | **[Tool Reference](https://docs.arc-1-mcp.com/tools/)** | **[ARC-1 Updates](https://docs.arc-1-mcp.com/newsletter/)** | **[Blog Series](https://blog.zeis.de/tags/ai-abap-development-series/)**
- > 📬 **Stay current with ARC-1** — get major releases, upgrade and security notes, practical guides, and occasional questions where your feedback can shape what comes next. **[Join ARC-1 Updates →](https://docs.arc-1-mcp.com/newsletter/)**
- > 📖 **New: AI ABAP Development blog series** — long-form posts on AI for ABAP, ARC-1 design, and real-world BTP / Copilot Studio / Joule walkthroughs. **[Read the series →](https://blog.zeis.de/tags/ai-abap-development-series/)**
- ## Why ARC-1?
- Built for organizations that need AI-assisted SAP development with guardrails. Inspired by the pioneering work of [abap-adt-api](https://github.com/marcellourbani/abap-adt-api), [mcp-abap-adt](https://github.com/mario-andreschak/mcp-abap-adt), and [vibing-steampunk](https://github.com/oisee/vibing-steampunk) — ARC-1 adds what's needed to run in production:
- ### Security & Admin Controls
- - **Safe by default** — read-only, no free SQL, no table preview, no transport writes, no Git writes. Enable each capability with explicit `SAP_ALLOW_*` flags
- - **Action deny list** — block specific tool actions with `SAP_DENY_ACTIONS` (for example `SAPWrite.delete`), without exposing low-level operation codes to admins
- - **Package restrictions** — limit AI write operations (create, update, delete) to specific packages with wildcards (`--allowed-packages "Z*,$TMP"`). Read operations are not restricted by package — use SAP's native authorization for read-level access control
- - **Data access control (off by default)** — table previews, saved SAPscript texts and SLG1 messages require `SAP_ALLOW_DATA_PREVIEW=true`; freestyle SQL separately requires `SAP_ALLOW_FREE_SQL=true`. Review enabled uses against the [SAP API Policy](docs_page/sap-api-policy-and-architecture.md), your SAP agreement, and internal data-governance rules.
- - **Experimental data-source emergency brake** — approved data/SQL deployments can set `SAP_BLOCKED_DATA_SOURCES=USR02,PA0002`. ARC-1 then parses each SQL request and resolves active CDS plus replacement-object lineage before execution, denying direct or transitive exact-name matches and failing closed when lineage is unsupported or cannot be proven. The empty default adds no metadata calls. This denylist is defense in depth, not a production allowlist or replacement for SAP authorization/CDS DCL; see [Authorization & Roles](docs_page/authorization.md#experimental-data-source-blocklist).
- - **Transport safety** — transport reads are available for review, while transport mutations require both `--allow-writes` and `--allow-transport-writes`. Update/delete operations auto-use the lock correction number when no explicit transport is provided
- - **Git workflow safety** — Git operations are disabled by default. Enable explicitly with `--allow-git-writes` / `SAP_ALLOW_GIT_WRITES=true`
- - **API-key profiles** — multi-key HTTP deployments can assign `viewer`, `viewer-data`, `viewer-sql`, `developer`, `developer-data`, `developer-sql`, or `admin` per key
- - **Writes restricted to `$TMP` when enabled** — only local/throwaway objects; writing to transportable packages requires explicit `--allowed-packages`
- - **HTTP security headers (helmet) on by default** — HSTS, CSP, X-Frame-Options, CORP, X-Content-Type-Options. COOP is deliberately not set so popup-based OAuth flows (Copilot Studio) keep working. No flag to disable.
- - **Opt-in CORS for browser MCP clients** — `ARC1_ALLOWED_ORIGINS` (comma-separated, exact match). Off by default; native MCP clients don't need it
- - **Opt-in client IP allowlist on SAP BTP Cloud Foundry** — `ARC1_ALLOWED_CLIENT_IPS` lets only listed addresses or CIDR ranges reach ARC-1, in front of authentication. Off by default; not suited to hosted clients such as Copilot Studio. [Setup and limits](docs_page/security-guide.md#client-ip-allowlist-sap-btp-cloud-foundry-opt-in)
- - **Layered rate limiting** — three layers out of the box: per-IP OAuth and shared MCP HTTP edge limits (Layer 1; MCP inherits the historical derived cap unless `ARC1_MCP_HTTP_RATE_LIMIT` overrides it), per-user MCP quota (Layer 2, **off by default** — multi-user deployments opt in via `ARC1_RATE_LIMIT=60`), and a server-wide SAP-bound semaphore (Layer 3, default 10, **on**). Honors `Retry-After` on 429/503 from SAP / BTP gateways. See the [Rate Limiting Guide](https://docs.arc-1-mcp.com/rate-limiting/)
- - **Dependency and release evidence** — Dependabot, npm audit and Dependency Review checks, CodeQL, Trivy container scanning, npm provenance, and a best-effort CycloneDX SBOM for the release's production npm lockfile graph. [Section 13 of the security guide](https://docs.arc-1-mcp.com/security-guide/#13-dependency-supply-chain-security) lists what each artifact covers, how to verify it, and the gaps. Vulnerability response targets are [best-effort and non-contractual](SECURITY.md).
- ### Authentication
- - **API key** — simple Bearer token for internal deployments
- - **OIDC / JWT** — Entra ID, Keycloak, or any OpenID Connect provider
- - **OAuth 2.0** — local browser-based login for BTP ABAP Environment service-key development
- - **XSUAA** — SAP BTP native auth with automatic token proxy for MCP clients
- - **Per-user SAP identity** — BTP Destination Service forwards the MCP user to SAP: Cloud Connector principal propagation for on-premise SAP, or `OAuth2UserTokenExchange` for BTP ABAP Environment
- ### BTP Cloud Foundry Deployment
- Deploy ARC-1 as a Cloud Foundry app on SAP BTP with full platform integration:
- - **Destination Service** — connect to SAP systems via managed destinations
- - **Experimental multi-target mode** — the default-off BTP mode discovers
- destinations marked `arc1.enabled=true` and exposes pinned SID/client plus read-only aggregate endpoints;
- [scoped pinned PP writes](docs_page/multi-target-writes.md) require separate destination/IAM opt-ins
- ([setup](docs_page/multi-target-setup.md),
- [administration](docs_page/multi-target-administration.md))
- - **Optional target filtering** — for shared multi-system gateways where teams need different target
- lists. [Assign systems/clients through XSUAA roles](docs_page/multi-target-authorization.md);
- IAS changes are optional. This filters IAM-assigned targets, not automatically discovered SAP accounts.
- - **Cloud Connector** — reach on-premise systems through the connectivity proxy
- - **Per-user destinations** — user identity forwarded end-to-end via X.509 certificates for on-premise SAP, or exchanged for an ABAP bearer token for BTP ABAP Environment
- - **XSUAA OAuth proxy** — MCP clients authenticate via standard OAuth, ARC-1 handles the BTP token exchange
- - **Audit logging** — structured events to stderr, file, or BTP Audit Log Service
- ### Token Efficiency
- - **12 intent-based tools** instead of 200+ individual tools — keeps tool selection simple, with the schema payload guarded by CI budgets and a hyperfocused 1-tool mode for tight context windows
- - **Method-level read/edit** — read or update a single class method, not the whole source (up to 20x fewer tokens)
- - **Focused source and dependency context** — use targeted `SAPRead` for exact implementation behavior. For business purpose, reviews or test design, start with `SAPContext(action="deps", type=..., name=...)` for available Knowledge Transfer Documents (`SKTD`/`KTD`) and dependency contracts, then compare requirements with source. Without documented requirements, intent is unverified.
- ### Built-in Object Caching
- - **Server-validated source caching** — every SAP object read is cached in memory (stdio) or SQLite (http-streamable). Repeated reads use `If-None-Match`/ETag conditional GET, so unchanged objects return from cache after SAP confirms `304 Not Modified`.
- - **Dependency parsing reuse** — unchanged, authorized source can reuse parsed dependencies and contracts in memory. Aggregate dependency graphs are not cached; SAP authorization and source validation still apply.
- - **KTD-aware context** — Knowledge Transfer Documents use the source cache and are revalidated when composed into `SAPContext(action="deps")`.
- - **Live where-used** — `SAPContext(action="usages")` and CDS impact analysis query SAP's current repository index with the caller's identity; no startup repository scan is required.
- - **Active/inactive source views** — `SAPRead` accepts `version="active" | "inactive" | "auto"` and warns when the active source has an unactivated draft.
- - **Write invalidation** — when `SAPWrite` or `SAPActivate` mutates an object, both active and inactive source cache entries are dropped; next read revalidates or fetches fresh source.
- See **[docs/caching.md](docs/caching.md)** for full documentation.
- ### Testing
- - **3,474 unit tests** (`104` unit test files, mocked HTTP)
- - **262-test default integration profile** against live SAP systems, with explicit skip reasons when credentials or fixtures are missing
- - **141-test default E2E profile** that executes real MCP tool calls against a running ARC-1 server and live SAP system
- - **Manual slow SAP profiles** keep broad where-used, RAP full-stack, and recursive CTS release coverage out of the PR path (`test:integration:slow`, `test:e2e:slow`, GitHub **SAP Slow Tests** workflow)
- - **CRUD lifecycle and BTP smoke lanes** included (`test:integration:crud`, `test:integration:btp:smoke`)
- - **CI matrix** on Node `22` and `24`; live SAP integration + E2E run on internal PRs and manual dispatch, with SAP jobs gated off for docs/chore PRs and external forks
- - **Reliability telemetry + coverage** published as informational CI signals (non-blocking)
- ### Tools Refined for Real-World Usage
- The 12 tools are designed from real LLM interaction feedback:
- | Tool | What it does |
- |------|-------------|
- | **SAPRead** | Read exact ABAP source, method bodies, grep matches, table data, CDS views, access controls (`DCLS`), metadata extensions (`DDLX`), service bindings (`SRVB`), knowledge-transfer docs (`SKTD` or friendly alias `KTD`), message classes (`MSAG`), revision history (`VERSIONS`/`VERSION_SOURCE`), inactive object state, BOR objects, deployed UI5/Fiori apps (BSP, BSP_DEPLOY), and ABAP Platform 2025 server-driven objects (`DESD`, `EVTB`, `EVTO`, `DTSC`, `CSNM`, `COTA`). For "what does this object do?" use `SAPContext` first, then `SAPRead` for precise source. Enhancement implementations (`ENHO`) are readable on-prem and on BTP; authorization fields (`AUTH`) and feature toggles (`FEATURE_TOGGLE`) are on-prem only. Structured format for classes returns metadata + decomposed includes as JSON. Optional `grep` regex returns only matching source lines (+context, method-annotated for classes) for token-efficient search. (Deprecated aliases `MESSAGES`/`FTG2` accepted for one minor.) |
- | **SAPSearch** | Object search + full-text source code search across the system |
- | **SAPWrite** | Create/update/delete ABAP source and DDIC metadata with automatic lock/unlock (PROG, CLAS, INTF, FUNC, FUGR, INCL, DDLS, DCLS, DDLX, BDEF, SRVD, SRVB, SKTD/KTD, TABL, DOMA, DTEL, MSAG; availability adapts for BTP). Class updates can target local includes (`definitions`, `implementations`, `macros`, `testclasses`); class-section surgery (`edit_class_definition`, `add_method`, `edit_method_signature`, `delete_method`, `change_method_visibility`) lets an LLM edit a global class signature without re-sending `/source/main`; RAP behavior-pool scaffolding can auto-create `lhc_*` skeletons before injecting signatures/stubs. Batch creation supports terminal activation for interdependent multi-object workflows (e.g., RAP stack or domain+data element in one call) |
- | **SAPActivate** | Activate ABAP objects — single or batch (essential for RAP stacks), with guarded retry for the S/4HANA ED064 batch quirk. Publish/unpublish OData service bindings (SRVB) |
- | **SAPNavigate** | Go-to-definition, find references, code completion |
- | **SAPQuery** | Read saved SAPscript long texts or execute ABAP SQL; each path requires its own opt-in |
- | **SAPTransport** | CTS transport management (list/get/create/release/delete/reassign/release-recursive), transport layer/target lookup, package transport requirement checks, and reverse lookup history (`action="history"`) |
- | **SAPGit** | Git-based ABAP workflows across gCTS and abapGit (list/clone/pull/push/commit/branch/unlink) with backend auto-selection and safety gating (`--allow-git-writes`) |
- | **SAPContext** | Dependency APIs (`action="deps"`): optional KTD plus bounded source-derived contracts, not a complete relationship inventory. Also supports live where-used (`action="usages"`), CDS impact (`action="impact"`), and TABL includes/appends (`action="structure"`) |
- | **SAPLint** | Local ABAP lint (system/release-aware presets, auto-fix, pre-write validation) + ADT PrettyPrint (server-side formatting) |
- | **SAPDiagnose** | Syntax check, ABAP Unit tests, ATC code quality, CDS test-case suggestions, active/inactive object-state comparison, generic ADT quickfix proposals/application deltas, gateway/system message diagnostics, short dumps, profiler traces, and the on-prem authorization trace (`SUAUTHVALTRC`, data-preview gated) |
- | **SAPManage** | Feature probing, cache statistics, package lifecycle/change-package operations, and FLP catalog/group/tile helpers |
- Tool definitions automatically adapt to the target system (BTP vs on-premise), removing unavailable types and adjusting descriptions so the LLM never attempts unsupported operations.
- ### Feature Detection
- ARC-1 probes the SAP system at startup and adapts its behavior:
- - Detects HANA, gCTS, abapGit, RAP/CDS, UI5, and transport availability
- - Auto-detects BTP vs on-premise systems
- - Maps SAP_BASIS release to the correct ABAP language version
- - Each feature can be forced on/off or left on auto-detect
- - In shared-credential mode (technical user), runs a startup auth preflight once and blocks SAP tool calls with a clear error on 401/403 to avoid repeated failed logins and potential user lockout
- ## ADT API Status and Strategy
- For a custom MCP server such as ARC-1, SAP's
- [Third-Party MCP Access reference architecture](https://architecture.learning.sap.com/docs/ref-arch/137800)
- is the primary design and control baseline we recommend. For a shared service, start with BTP Cloud
- Foundry, XSUAA and strict principal propagation. SAP's API Policy FAQ Q56 allows custom MCP servers
- under conditions; Q32 confirms that Integration Suite is not mandatory.
- **[SAP API Policy & Architecture Alignment](docs_page/sap-api-policy-and-architecture.md)** explains
- that path, the controls ARC-1 already supports, and the remaining gaps. FAQ Q33 classifies ADT APIs
- as internal and limits them to endorsed development channels; ARC-1's direct TypeScript ADT client
- is not specifically identified as one. Clarify that channel and the intended AI-assisted development
- use with SAP before adoption, including dev/test. BTP hosting and security controls alone do not
- establish full policy adherence. Per-user SAP identity applies to PP; shared Basic modes retain a
- shared SAP identity.
- Two ARC-1 capabilities can expose business data or execute ad-hoc SQL. Both are **off by default** and require explicit opt-in env vars, so the operator makes a deliberate decision before they are reachable:
- | Capability | Env var | Default | Policy note |
- | ---------- | ------- | ------- | ----------- |
- | Table previews (`SAPRead(type=TABLE_CONTENTS/TABLE_QUERY)`), [saved SAPscript texts](docs_page/tools.md#stored-sapscript-long-texts) and [SLG1 messages](docs_page/tools.md#saved-application-logs-actionapplication_log) (`SAPQuery` actions `long_text` / `application_log`) | `SAP_ALLOW_DATA_PREVIEW=true` | `false` (off) | Reads application data; authenticated callers also need `data` scope. |
- | Freestyle ABAP SQL (`SAPQuery(action=sql)`) | `SAP_ALLOW_FREE_SQL=true` | `false` (off) | Executes ad-hoc ABAP SQL; authenticated callers also need `sql` scope. |
- | Exact source blocklist (experimental) | `SAP_BLOCKED_DATA_SOURCES=USR02,PA0002` | empty (off) | Denies exact direct/transitive table or CDS dependencies; active mode is deliberately fail-closed and slower. |
- When either capability is enabled, successful data-preview bodies are limited cumulatively per tool
- call (2 MiB by default), and only two data-result calls per process remain admitted through parsing
- and serialization. `SAPQuery.maxRows` is separately clamped to 10,000, but wide rows can reach the
- byte limit much earlier. See [Configuration](docs_page/configuration-reference.md) before tuning
- `ARC1_MAX_DATAPREVIEW_RESPONSE_BYTES` or `ARC1_MAX_CONCURRENT_DATA_RESULTS`.
- With both flags at their defaults, ARC-1's data/sql rows are unreachable. FAQ Q33 excludes application-table
- reads, business-data export and backend SQL from ADT's intended development-tooling scope. Keep these
- flags off unless the specific use has a documented allowance or SAP authorization under the applicable
- agreements; internal approval or a technical opt-in alone is insufficient. Use Published business APIs
- for business-data integration.
- ARC-1 combines capability discovery with conservative defaults and centralized authorization. Discovery establishes technical availability, not API-policy permission. Follow the reference architecture and verify both the API-specific allowance and the deployed controls.
- ## Versioning & Stability
- From `1.0` onward ARC-1 follows [semantic versioning](https://semver.org/): patch releases fix bugs, minor releases add backward-compatible capability, and breaking changes to the MCP tool surface, configuration, or auth contract bump the major version.
- **Experimental, default-off features are excluded from this guarantee until they are promoted** — they are clearly labeled and their surface may still change in a minor release. Today this covers the [multi-target BTP mode](docs_page/multi-target-setup.md) (ADR-0006 / ADR-0007) and the [data-source blocklist](docs_page/authorization.md#experimental-data-source-blocklist).
- What changed per release: the annotated [Release Notes](https://docs.arc-1-mcp.com/release-notes/) give each release its impact and upgrade action; [CHANGELOG.md](CHANGELOG.md) lists every merged PR.
- ## Quick Start
- **Install as an Agent Plugin** — one portable install for the MCP server and all bundled SAP skills in
- GitHub Copilot, VS Code, Cursor, Codex, and other compatible clients:
- ```bash
- copilot plugin marketplace add arc-mcp/arc-1
- copilot plugin install arc-1@arc-1
- ```
- Agent Plugins 1.0 does not define secret prompts, so create the ARC-1 `.env` in the installed
- plugin's persistent data directory before connecting to SAP. See the
- **[Agent Plugin guide](https://docs.arc-1-mcp.com/agent-plugin/)** for client-specific installation,
- safe configuration, and verification.
- **Install in Claude** — pick your surface (full guide: [Install in Claude](https://docs.arc-1-mcp.com/install-in-claude/)):
- - **Claude Desktop** — download the latest `arc-1-*.mcpb` from [Releases](https://github.com/arc-mcp/arc-1/releases) and double-click it (or Settings → Extensions). Claude prompts for your SAP connection. (The `.mcpb` is attached to releases automatically; if the newest one doesn't have it yet, see [Install in Claude](https://docs.arc-1-mcp.com/install-in-claude/).)
- - **Claude Code** — one install for the MCP server **and** all [SAP skills](https://github.com/arc-mcp/arc-1/tree/main/skills):
- ```text
- /plugin marketplace add arc-mcp/arc-1
- /plugin install arc-1@arc-1
- ```
- - **Any MCP client / manual** — run it directly:
- ```bash
- npx arc-1@latest --url https://your-sap-host:44300 --user YOUR_USER
- ```
- - **Trying it out on your laptop?** → [Quickstart](https://docs.arc-1-mcp.com/quickstart/)
- - **Full local dev setup (Docker, cookie extractor, client configs)?** → [Local Development](https://docs.arc-1-mcp.com/local-development/)
- - **Deploying for a team / BTP?** → [Deployment](https://docs.arc-1-mcp.com/deployment/)
- ## Blog Series — AI ABAP Development
- A long-form series on [blog.zeis.de](https://blog.zeis.de/tags/ai-abap-development-series/) covering AI for ABAP development, ARC-1's design, and real-world walkthroughs:
- 1. [How I Use AI for Development and Why Context Matters](https://blog.zeis.de/posts/2026-04-20-how-i-use-ai/)
- 2. [ABAP and Agentic AI: The Hidden Problem in Real Projects](https://blog.zeis.de/posts/2026-04-22-ai-abap-development/)
- 3. [Introducing ARC-1: A Secure ADT MCP Server for Enterprise SAP Development](https://blog.zeis.de/posts/2026-04-27-arc-1/)
- 4. [ARC-1 on SAP BTP: Secure ABAP Agentic Development Beyond the Laptop](https://blog.zeis.de/posts/2026-04-29-arc-1-btp/)
- 5. [ARC-1 with Copilot Studio: SAP System Context Beyond Developers](https://blog.zeis.de/posts/2026-05-05-arc-1-copilot-studio/)
- 6. [ARC-1 with Joule Studio: Bringing Real ABAP System Context into Joule](https://blog.zeis.de/posts/2026-05-08-arc-1-joule-studio-clean-core/)
- 7. [From SEGW and Legacy UI5 to RAP with ARC-1](https://blog.zeis.de/posts/2026-05-11-segw-to-rap/)
- Full list and new posts → **[blog.zeis.de/tags/ai-abap-development-series](https://blog.zeis.de/tags/ai-abap-development-series/)**.
- ## Documentation
- Full documentation is available at **[docs.arc-1-mcp.com](https://docs.arc-1-mcp.com/)**.
- | Guide | Description |
- |-------|-------------|
- | [Quickstart](https://docs.arc-1-mcp.com/quickstart/) | 5-minute npx + Claude Desktop setup |
- | [Agent Plugin](https://docs.arc-1-mcp.com/agent-plugin/) | Portable server + all skills for Copilot, VS Code, Cursor, Codex, and compatible clients |
- | [Install in Claude](https://docs.arc-1-mcp.com/install-in-claude/) | Desktop `.mcpb`, Claude Code plugin (server + skills), and remote BTP connector |
- | [Local Development](https://docs.arc-1-mcp.com/local-development/) | Full local dev — all install methods, MCP client configs, SSO cookie extractor |
- | [Deployment](https://docs.arc-1-mcp.com/deployment/) | Multi-user deployment — Docker, BTP Cloud Foundry, BTP ABAP |
- | [SAP BTP: Start Here](https://docs.arc-1-mcp.com/btp-overview/) | Choose the BTP topology and follow the correct deployment, auth, destination, and operations guides |
- | [BTP Cloud Foundry](https://docs.arc-1-mcp.com/btp-cloud-foundry-deployment/) | MTA deployment, topology decision, role handoffs, and safe acceptance |
- | [BTP Administration](https://docs.arc-1-mcp.com/btp-administration/) | Changes, roles, secrets, scaling, upgrades, rollback, and customer handover |
- | [Multi-System Setup](https://docs.arc-1-mcp.com/multi-target-setup/) | BTP multi-target deployment, destinations, roles, and scoped pinned PP writes |
- | [Configuration](https://docs.arc-1-mcp.com/configuration-reference/) | Every flag and env var, one table |
- | [Updating](https://docs.arc-1-mcp.com/updating/) | Update procedures per install method |
- | [Enterprise Auth](https://docs.arc-1-mcp.com/enterprise-auth/) | Layer A / Layer B auth internals, coexistence matrix |
- | [Tool Reference](https://docs.arc-1-mcp.com/tools/) | Complete reference for all 12 tools |
- | [Extensions (Custom Tools)](https://docs.arc-1-mcp.com/extensions/) | Add your own `Custom_*` tools without forking (FEAT-61) — reads, gated non-ADT writes, class/report execute |
- | [Architecture](https://docs.arc-1-mcp.com/architecture/) | System architecture with diagrams |
- | [AI Usage Patterns](https://docs.arc-1-mcp.com/mcp-usage/) | Agent workflow patterns and best practices |
- | [Skills](https://docs.arc-1-mcp.com/skills/) | Reusable ARC-1 agent skills, including GitHub Copilot in Eclipse and VS Code ADT setup |
- | [Blog Series](https://docs.arc-1-mcp.com/blog-series/) | Long-form posts on AI for ABAP development, ARC-1 internals, and real-world walkthroughs |
- ## Development
- ```bash
- npm ci && npm run build && npm test
- ```
- See [CLAUDE.md](CLAUDE.md) for codebase structure, testing commands, and contribution guidelines.
- ## Credits
- | Project | Author | Contribution |
- |---------|--------|--------------|
- | [vibing-steampunk](https://github.com/oisee/vibing-steampunk) | oisee | Original Go MCP server — ARC-1's starting point |
- | [abap-adt-api](https://github.com/marcellourbani/abap-adt-api) | Marcello Urbani | TypeScript ADT library, definitive API reference |
- | [mcp-abap-adt](https://github.com/mario-andreschak/mcp-abap-adt) | Mario Andreschak | First MCP server for ABAP ADT |
- | [abaplint](https://github.com/abaplint/abaplint) | Lars Hvam | ABAP parser/linter (used via @abaplint/core) |
- ## License
- MIT
scripts/e2e-deploy.sh · Bundled script · 276 lines · 1 finding marked
- #!/usr/bin/env bash
- # scripts/e2e-deploy.sh
- # Deploys dist/ to the E2E test server, starts MCP server under exclusive lock.
- # The lock prevents multiple callers (local devs, CI) from colliding.
- set -euo pipefail
- SERVER="${E2E_SERVER:?E2E_SERVER must be set}"
- SERVER_USER="${E2E_SERVER_USER:?E2E_SERVER_USER must be set}"
- DEPLOY_DIR="/opt/arc1-e2e"
- LOCKFILE="/tmp/arc1-e2e.lock"
- LOCK_TIMEOUT="${E2E_LOCK_TIMEOUT:-300}"
- MCP_PORT="${E2E_MCP_PORT:-3000}"
- LOG_DIR="${E2E_LOG_DIR:-/tmp/arc1-e2e-logs}"
- SSH_OPTS="-o StrictHostKeyChecking=no -o ConnectTimeout=10"
- # Mask server address in logs (CI logs are public)
- MASKED_SERVER="$(echo "${SERVER}" | sed 's/[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}/***.***/g')"
- mkdir -p "${LOG_DIR}"
- echo ""
- echo "======================================================================"
- echo " E2E Deploy"
- echo "======================================================================"
- echo ""
- echo " Server: ***@${MASKED_SERVER}"
- echo " Deploy dir: ${DEPLOY_DIR}"
- echo " MCP port: ${MCP_PORT}"
- echo " Lock file: ${LOCKFILE} (timeout: ${LOCK_TIMEOUT}s)"
- echo " Local logs: ${LOG_DIR}/"
- echo ""
- # ── Pre-flight: SSH ─────────────────────────────────────────────────
- echo "-- Checking SSH connectivity..."
- if ! ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} "echo ok" > /dev/null 2>&1; then
- echo "ERROR: Cannot SSH to server"
- echo " - Is the server running?"
- echo " - Is your SSH key configured? (~/.ssh/id_rsa or id_ed25519)"
- echo " - Try: ssh \$E2E_SERVER_USER@\$E2E_SERVER"
- exit 1
- fi
- echo " SSH: OK"
- # ── Pre-flight: Write SAP password to server ──────────────────────
- # Must happen before DB health check so curl can authenticate.
- echo "-- Writing SAP credentials to server..."
- ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} \
- "echo -n '${SAP_PASSWORD:?SAP_PASSWORD must be set}' > ${DEPLOY_DIR}/.sap_password && chmod 600 ${DEPLOY_DIR}/.sap_password"
- echo " .sap_password: written"
- # ── Pre-flight: SAP (ICM + DB health) ──────────────────────────────
- echo "-- Checking SAP system..."
- SAP_STATUS=$(ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} \
- "curl -s -o /dev/null -w '%{http_code}' http://localhost:50000/sap/bc/adt/discovery 2>/dev/null || echo '000'")
- if [ "$SAP_STATUS" = "000" ]; then
- echo "ERROR: SAP system not reachable at localhost:50000"
- echo " - Check Docker container: ssh \$E2E_SERVER_USER@\$E2E_SERVER 'docker ps | grep a4h'"
- echo " - Start SAP: ssh \$E2E_SERVER_USER@\$E2E_SERVER 'docker start a4h'"
- exit 1
- fi
- echo " ICM: OK (HTTP ${SAP_STATUS})"
- # Deep health check: test DB-dependent ADT calls across multiple work processes.
- # SAP load-balances requests across work processes — a single request might hit a
- # healthy WP while others have broken HANA connections. We send multiple requests
- # to cover more work processes. If ANY fail, trigger recovery.
- echo "-- Checking ABAP work process DB connections (10 requests)..."
- DB_CHECK_RESULT=$(ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} bash -s "${SAP_USER}" <<'DB_CHECK'
- SAP_USER="$1"
- SAP_PASS=$(cat /opt/arc1-e2e/.sap_password 2>/dev/null)
- FAILURES=0
- AUTH_FAIL=0
- for i in $(seq 1 10); do
- BODY=$(curl -s -u "${SAP_USER}:${SAP_PASS}" \
- "http://localhost:50000/sap/bc/adt/programs/programs/RSHOWTIM/source/main" 2>/dev/null)
- if echo "$BODY" | grep -qi "database connection is not open"; then
- FAILURES=$((FAILURES + 1))
- elif echo "$BODY" | grep -qi "Anmeldung fehlgeschlagen\|401"; then
- AUTH_FAIL=$((AUTH_FAIL + 1))
- fi
- done
- echo "FAILURES=${FAILURES} AUTH_FAIL=${AUTH_FAIL}"
- DB_CHECK
- )
- DB_FAILURES=$(echo "${DB_CHECK_RESULT}" | grep -oP 'FAILURES=\K[0-9]+' || echo "0")
- DB_AUTH_FAIL=$(echo "${DB_CHECK_RESULT}" | grep -oP 'AUTH_FAIL=\K[0-9]+' || echo "0")
- if [ "${DB_FAILURES}" -gt "0" ]; then
- echo " WARNING: ${DB_FAILURES}/10 requests hit broken HANA DB connections"
- echo " Attempting recovery: stopping + restarting ABAP instance..."
- ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} bash <<'RECOVER'
- # Full instance Stop + Start restarts all work processes and re-establishes
- # DB connections. RestartService alone doesn't always fix all WPs.
- docker exec a4h su - a4hadm -c "sapcontrol -nr 00 -function Stop" 2>/dev/null || true
- echo " Waiting for ABAP to stop..."
- for i in $(seq 1 30); do
- sleep 5
- STATUS=$(docker exec a4h su - a4hadm -c "sapcontrol -nr 00 -function GetProcessList" 2>&1 || echo "")
- if echo "$STATUS" | grep -q "GRAY" && ! echo "$STATUS" | grep -q "GREEN"; then
- echo " ABAP stopped after $((i*5))s"
- break
- fi
- done
- docker exec a4h su - a4hadm -c "sapcontrol -nr 00 -function Start" 2>/dev/null || true
- echo " Waiting for ABAP to start..."
- for i in $(seq 1 90); do
- sleep 5
- STATUS=$(docker exec a4h su - a4hadm -c "sapcontrol -nr 00 -function GetProcessList" 2>&1 || echo "")
- GREEN_COUNT=$(echo "$STATUS" | grep -c "GREEN" || true)
- if [ "$GREEN_COUNT" -ge 4 ]; then
- echo " All processes GREEN after $((i*5))s"
- break
- fi
- done
- RECOVER
- # Re-check after recovery
- sleep 10
- RECHECK=$(ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} bash -s "${SAP_USER}" <<'RECHECK_SCRIPT'
- SAP_USER="$1"
- SAP_PASS=$(cat /opt/arc1-e2e/.sap_password 2>/dev/null)
- FAILURES=0
- for i in $(seq 1 10); do
- BODY=$(curl -s -u "${SAP_USER}:${SAP_PASS}" \
- "http://localhost:50000/sap/bc/adt/programs/programs/RSHOWTIM/source/main" 2>/dev/null)
- if echo "$BODY" | grep -qi "database connection is not open"; then
- FAILURES=$((FAILURES + 1))
- fi
- done
- echo "$FAILURES"
- RECHECK_SCRIPT
- )
- if [ "${RECHECK}" -gt "0" ]; then
- echo " ERROR: Recovery failed — ${RECHECK}/10 requests still hit broken DB connections"
- echo " Manual fix: ssh \$E2E_SERVER_USER@\$E2E_SERVER 'docker stop -t 7200 a4h && docker start a4h'"
- exit 1
- fi
- echo " DB: OK (recovered after ABAP instance restart)"
- elif [ "${DB_AUTH_FAIL}" -gt "0" ]; then
- echo " ERROR: DB check got ${DB_AUTH_FAIL}/10 auth failures (HTTP 401)"
- echo " The SAP_USER + SAP_PASSWORD combination is rejected by the SAP system."
- echo " Verify that the SAP_USER secret matches the user whose password is in SAP_PASSWORD."
- echo " (e.g., if SAP_PASSWORD is for DEVELOPER, SAP_USER must also be DEVELOPER)"
- exit 1
- else
- echo " DB: OK (10/10 requests successful)"
- fi
- # ── Pre-flight: Lock (stale detection) ─────────────────────────────
- MAX_LOCK_AGE="${E2E_MAX_LOCK_AGE:-900}" # 15 minutes — e2e suite takes ~6 min
- echo "-- Checking lock status..."
- LOCK_INFO=$(ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} "cat ${LOCKFILE}.info 2>/dev/null || echo 'no active lock'")
- echo " Lock: ${LOCK_INFO}"
- # Break stale locks: if the locking PID is dead or the lock is older than MAX_LOCK_AGE
- ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} bash -s "${LOCKFILE}" "${MAX_LOCK_AGE}" <<'STALE_CHECK'
- LOCKFILE="$1"
- MAX_AGE="$2"
- INFO_FILE="${LOCKFILE}.info"
- [ ! -f "$INFO_FILE" ] && exit 0
- # Extract PID from lock info
- LOCK_PID=$(grep -oP 'PID: \K[0-9]+' "$INFO_FILE" 2>/dev/null || echo "")
- if [ -z "$LOCK_PID" ]; then
- exit 0
- fi
- # Check 1: Is the locking process still alive?
- if ! kill -0 "$LOCK_PID" 2>/dev/null; then
- echo " STALE LOCK: PID $LOCK_PID is dead — breaking lock"
- rm -f "$LOCKFILE" "$INFO_FILE"
- # Also kill any orphaned MCP server (glob pattern matches both absolute/relative paths)
- pkill -f 'node.*dist/index.js' 2>/dev/null || true
- fuser -k 3000/tcp 2>/dev/null || true
- exit 0
- fi
- # Check 2: Is the lock older than MAX_AGE?
- if [ -f "$INFO_FILE" ]; then
- LOCK_MTIME=$(stat -c %Y "$INFO_FILE" 2>/dev/null || echo 0)
- NOW=$(date +%s)
- AGE=$(( NOW - LOCK_MTIME ))
- if [ "$AGE" -gt "$MAX_AGE" ]; then
- echo " STALE LOCK: age ${AGE}s exceeds max ${MAX_AGE}s — breaking lock"
- kill "$LOCK_PID" 2>/dev/null || true
- pkill -f 'node.*dist/index.js' 2>/dev/null || true
- fuser -k 3000/tcp 2>/dev/null || true
- sleep 2
- rm -f "$LOCKFILE" "$INFO_FILE"
- exit 0
- fi
- fi
- STALE_CHECK
- # ── Pre-flight: Node.js ─────────────────────────────────────────────
- echo "-- Checking Node.js on server..."
- NODE_VERSION=$(ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} "node --version 2>/dev/null || echo 'MISSING'")
- if [ "$NODE_VERSION" = "MISSING" ]; then
- echo "ERROR: Node.js not installed on server"
- echo " Install: ssh \$E2E_SERVER_USER@\$E2E_SERVER 'curl -fsSL https://deb.nodesource.com/setup_22.x | bash - && apt-get install -y nodejs'"
- Note: Pipes a downloaded script directly into a shell (curl | sh / wget | bash)
- Line 200 on GitHub
- exit 1
- fi
- echo " Node: ${NODE_VERSION}"
- # ── Sync files ──────────────────────────────────────────────────────
- echo ""
- echo "-- Syncing dist/ to server..."
- rsync -az --delete -e "ssh ${SSH_OPTS}" dist/ ${SERVER_USER}@${SERVER}:${DEPLOY_DIR}/dist/
- echo " dist/: synced"
- echo "-- Syncing node_modules/..."
- # Exclude better-sqlite3: native addon compiled for CI's Node ABI won't load on
- # the e2e server. The e2e server starts with ARC1_CACHE=memory, and server.ts
- # loads SqliteCache dynamically so a missing better-sqlite3 is gracefully handled.
- rsync -az --delete --exclude='better-sqlite3' -e "ssh ${SSH_OPTS}" node_modules/ ${SERVER_USER}@${SERVER}:${DEPLOY_DIR}/node_modules/
- echo " node_modules/: synced (excluding better-sqlite3)"
- scp -q ${SSH_OPTS} package.json ${SERVER_USER}@${SERVER}:${DEPLOY_DIR}/
- echo " package.json: copied"
- # Upload the server-side start script (avoids nested quoting issues)
- SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
- scp -q ${SSH_OPTS} "${SCRIPT_DIR}/e2e-server-start.sh" ${SERVER_USER}@${SERVER}:${DEPLOY_DIR}/start.sh
- ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} "chmod +x ${DEPLOY_DIR}/start.sh"
- echo " start.sh: uploaded"
- # ── Acquire lock + start server ─────────────────────────────────────
- echo ""
- echo "-- Acquiring lock (waiting up to ${LOCK_TIMEOUT}s if another run is active)..."
- ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} \
- "SAP_USER='${SAP_USER:?SAP_USER must be set}' flock --timeout ${LOCK_TIMEOUT} ${LOCKFILE} ${DEPLOY_DIR}/start.sh" \
- || {
- RC=$?
- echo ""
- echo "ERROR: Could not acquire lock or start server (exit code: ${RC})"
- echo ""
- LOCK_INFO=$(ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} "cat ${LOCKFILE}.info 2>/dev/null || echo '(no lock info)'")
- echo "Lock info: ${LOCK_INFO}"
- echo ""
- # Show server log if it exists
- SERVER_LOG=$(ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} "tail -20 /tmp/arc1-e2e.log 2>/dev/null || echo '(no server log)'")
- echo "Server log (last 20 lines):"
- echo "${SERVER_LOG}"
- echo ""
- echo "Options:"
- echo " 1. Wait for the other run to finish"
- echo " 2. Force stop: npm run test:e2e:stop"
- exit 1
- }
- # ── Post-deploy: Verify server identity ────────────────────────────
- echo ""
- echo "-- Verifying deployed server identity..."
- HEALTH_JSON=$(ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} \
- "curl -sf http://localhost:${MCP_PORT}/health 2>/dev/null || echo '{}'")
- HEALTH_PID=$(echo "${HEALTH_JSON}" | grep -oP '"pid":\s*\K[0-9]+' || echo "unknown")
- HEALTH_VERSION=$(echo "${HEALTH_JSON}" | grep -oP '"version":\s*"\K[^"]+' || echo "unknown")
- HEALTH_STARTED=$(echo "${HEALTH_JSON}" | grep -oP '"startedAt":\s*"\K[^"]+' || echo "unknown")
- EXPECTED_PID=$(ssh ${SSH_OPTS} ${SERVER_USER}@${SERVER} "cat /tmp/arc1-e2e.pid 2>/dev/null || echo 'unknown'")
- if [ "$HEALTH_PID" != "$EXPECTED_PID" ] && [ "$HEALTH_PID" != "unknown" ]; then
- echo " FATAL: Health endpoint reports PID ${HEALTH_PID} but we started PID ${EXPECTED_PID}"
- echo " A zombie process is serving on port ${MCP_PORT}!"
- echo " Health response: ${HEALTH_JSON}"
- exit 1
- fi
- echo ""
- echo "======================================================================"
- echo " MCP server running on port ${MCP_PORT}"
- echo " PID: ${HEALTH_PID}"
- echo " Version: ${HEALTH_VERSION}"
- echo " Started: ${HEALTH_STARTED}"
- echo "======================================================================"
- echo ""
scripts/probe-issue-303.mjs · Bundled script · 692 lines · 2 findings marked
- // scripts/probe-issue-303.mjs — verify the 4-action plan against a real SAP system.
- //
- // Exercises against a fresh probe class:
- // 1. edit_class_definition happy path (no method-set change)
- // 2. edit_class_definition refuse-policy SAP-side evidence (added method w/o stub → activation rejected)
- // 3. edit_class_definition refuse-policy SAP-side evidence (orphan impl → activation rejected)
- // 4. add_method (public section)
- // 5. add_method into a missing PROTECTED section (refuse case — verify section detection)
- // 6. edit_method_signature (one-range replace)
- // 7. delete_method (delete both ranges)
- //
- // All operations roundtrip through objectstructure → splice → PUT /source/main.
- //
- // Usage: node scripts/probe-issue-303.mjs <system>
- Note: Usual in code (tag names in paths and patterns): Contains a <system> block, a common wrapper for instructions hidden in a tool description
- Line 14 on GitHub
- // <system> ∈ { a4h, npl }
- Note: Usual in code (tag names in paths and patterns): Contains a <system> block, a common wrapper for instructions hidden in a tool description
- Line 15 on GitHub
- //
- // Outputs each step's PASS/FAIL/SAP_RESPONSE and a final summary.
- import 'dotenv/config';
- import { fetch, Agent } from 'undici';
- import { readFileSync } from 'node:fs';
- const SYSTEM = process.argv[2] ?? 'a4h';
- // Credentials come from env only — never hardcode them here.
- // a4h: SAP_URL / SAP_USER / SAP_PASSWORD / SAP_CLIENT (loaded from .env via dotenv)
- // npl: NPL_URL / NPL_USER / NPL_PASSWORD / NPL_CLIENT
- // See INFRASTRUCTURE.md for the test-system endpoints + credential locations.
- const sysConfig = {
- a4h: {
- url: process.env.SAP_URL,
- user: process.env.SAP_USER,
- password: process.env.SAP_PASSWORD,
- client: process.env.SAP_CLIENT ?? '001',
- className: 'ZCL_ARC1_PROBE303',
- },
- npl: {
- url: process.env.NPL_URL ?? 'https://npl.marianzeis.de',
- user: process.env.NPL_USER,
- password: process.env.NPL_PASSWORD,
- client: process.env.NPL_CLIENT ?? '001',
- className: 'ZCL_ARC1_PROBE303',
- },
- };
- const cfg = sysConfig[SYSTEM];
- if (!cfg) throw new Error(`unknown system ${SYSTEM}`);
- if (!cfg.url || !cfg.user || !cfg.password) {
- const prefix = SYSTEM === 'npl' ? 'NPL' : 'SAP';
- throw new Error(
- `Missing credentials for ${SYSTEM}. Set ${prefix}_URL, ${prefix}_USER, ${prefix}_PASSWORD (a4h reads SAP_* from .env; npl reads NPL_*).`,
- );
- }
- const auth = 'Basic ' + Buffer.from(`${cfg.user}:${cfg.password}`).toString('base64');
- const dispatcher = new Agent({ connect: { rejectUnauthorized: false } });
- let cookies = '';
- const collectCookies = (resp) => {
- for (const c of resp.headers.getSetCookie?.() ?? []) {
- const pair = c.indexOf(';') >= 0 ? c.slice(0, c.indexOf(';')) : c;
- cookies = cookies ? cookies + '; ' + pair : pair;
- }
- };
- async function http(method, path, opts = {}) {
- const url = `${cfg.url}${path}${path.includes('?') ? '&' : '?'}sap-client=${cfg.client}`;
- const headers = { Authorization: auth, ...(opts.headers ?? {}) };
- if (cookies) headers.Cookie = cookies;
- const r = await fetch(url, { method, headers, body: opts.body, dispatcher });
- collectCookies(r);
- const text = await r.text();
- return { status: r.status, text, headers: r.headers };
- }
- let csrf;
- async function fetchCsrf() {
- const r = await http('GET', '/sap/bc/adt/discovery', { headers: { 'X-CSRF-Token': 'Fetch', Accept: 'application/atomsvc+xml' } });
- csrf = r.headers.get('x-csrf-token');
- if (!csrf) throw new Error(`CSRF fetch failed: status=${r.status} csrf=${csrf} body=${r.text.slice(0, 200)}`);
- return csrf;
- }
- async function deleteProbe() {
- const objPath = `/sap/bc/adt/oo/classes/${cfg.className}`;
- // Lock first.
- const lock = await http('POST', `${objPath}?_action=LOCK&accessMode=MODIFY`, {
- headers: { 'X-CSRF-Token': csrf, Accept: 'application/vnd.sap.as+xml; charset=UTF-8; dataname=com.sap.adt.lock.Result2', 'X-sap-adt-sessiontype': 'stateful' },
- });
- if (lock.status >= 400) {
- if (lock.status === 404) return false; // didn't exist
- console.log(` preexisting class lock failed: ${lock.status} ${lock.text.slice(0, 200)}`);
- return false;
- }
- const lockHandle = lock.text.match(/<LOCK_HANDLE>([^<]+)<\/LOCK_HANDLE>/)?.[1];
- const del = await http('DELETE', `${objPath}?lockHandle=${encodeURIComponent(lockHandle)}`, {
- headers: { 'X-CSRF-Token': csrf, 'X-sap-adt-sessiontype': 'stateful' },
- });
- return del.status < 300;
- }
- async function createProbe() {
- const objPath = '/sap/bc/adt/oo/classes';
- const payload = `<?xml version="1.0" encoding="UTF-8"?>
- <class:abapClass xmlns:class="http://www.sap.com/adt/oo/classes"
- xmlns:adtcore="http://www.sap.com/adt/core"
- class:final="true"
- class:visibility="public"
- adtcore:name="${cfg.className}"
- adtcore:type="CLAS/OC"
- adtcore:description="Probe for issue 303 plan verification"
- adtcore:masterLanguage="EN"
- adtcore:masterSystem="A4H">
- <adtcore:packageRef adtcore:name="$TMP"/>
- </class:abapClass>`;
- const r = await http('POST', objPath, {
- headers: {
- 'Content-Type': 'application/vnd.sap.adt.oo.classes.v4+xml',
- Accept: 'application/vnd.sap.adt.oo.classes.v4+xml',
- 'X-CSRF-Token': csrf,
- },
- body: payload,
- });
- if (r.status >= 400) throw new Error(`create failed: ${r.status} ${r.text.slice(0, 400)}`);
- return r;
- }
- async function lockClass() {
- const objPath = `/sap/bc/adt/oo/classes/${cfg.className}`;
- const r = await http('POST', `${objPath}?_action=LOCK&accessMode=MODIFY`, {
- headers: { 'X-CSRF-Token': csrf, Accept: 'application/vnd.sap.as+xml; charset=UTF-8; dataname=com.sap.adt.lock.Result2', 'X-sap-adt-sessiontype': 'stateful' },
- });
- if (r.status >= 400) throw new Error(`lock failed: ${r.status} ${r.text.slice(0, 400)}`);
- return {
- lockHandle: r.text.match(/<LOCK_HANDLE>([^<]+)<\/LOCK_HANDLE>/)?.[1],
- corrNr: r.text.match(/<CORRNR>([^<]+)<\/CORRNR>/)?.[1],
- };
- }
- async function unlockClass(lockHandle) {
- const objPath = `/sap/bc/adt/oo/classes/${cfg.className}`;
- await http('POST', `${objPath}?_action=UNLOCK&lockHandle=${encodeURIComponent(lockHandle)}`, {
- headers: { 'X-CSRF-Token': csrf, 'X-sap-adt-sessiontype': 'stateful' },
- });
- }
- async function putMain(source, lockHandle, corrNr) {
- const objPath = `/sap/bc/adt/oo/classes/${cfg.className}`;
- const qs = `?lockHandle=${encodeURIComponent(lockHandle)}${corrNr ? `&corrNr=${encodeURIComponent(corrNr)}` : ''}`;
- return await http('PUT', `${objPath}/source/main${qs}`, {
- headers: { 'X-CSRF-Token': csrf, 'Content-Type': 'text/plain; charset=utf-8', Accept: 'text/plain', 'X-sap-adt-sessiontype': 'stateful' },
- body: source,
- });
- }
- async function getMain() {
- const objPath = `/sap/bc/adt/oo/classes/${cfg.className}`;
- const r = await http('GET', `${objPath}/source/main`, { headers: { Accept: 'text/plain' } });
- return r.text;
- }
- async function getObjectStructure() {
- const objPath = `/sap/bc/adt/oo/classes/${cfg.className}`;
- const r = await http('GET', `${objPath}/objectstructure`, {
- headers: { Accept: 'application/vnd.sap.adt.objectstructure.v2+xml' },
- });
- if (r.status >= 400) throw new Error(`objectstructure failed: ${r.status} ${r.text.slice(0, 200)}`);
- return r.text;
- }
- // Activate via the ADT activation endpoint.
- async function activate() {
- const objUri = `/sap/bc/adt/oo/classes/${cfg.className.toLowerCase()}`;
- const payload = `<?xml version="1.0" encoding="UTF-8"?>
- <adtcore:objectReferences xmlns:adtcore="http://www.sap.com/adt/core">
- <adtcore:objectReference adtcore:uri="${objUri}" adtcore:name="${cfg.className}"/>
- </adtcore:objectReferences>`;
- return await http('POST', '/sap/bc/adt/activation?method=activate&preauditRequested=true', {
- headers: { 'Content-Type': 'application/xml', Accept: 'application/xml', 'X-CSRF-Token': csrf },
- body: payload,
- });
- }
- // ── Structure parsing ─────────────────────────────────────────────────────────
- function parseRange(href) {
- const m = href.match(/#start=(\d+),(\d+);end=(\d+),(\d+)/);
- if (!m) return null;
- return { sr: +m[1], sc: +m[2], er: +m[3], ec: +m[4] };
- }
- function parseObjectStructure(xml) {
- const result = { class: {}, methods: [], attributes: [] };
- // Class-level blocks: the FIRST `definitionBlock` and FIRST `implementationBlock` in document order
- // are the class-level ones (they precede any nested `<objectStructureElement>`).
- const defMatch = xml.match(/rel="http:\/\/www\.sap\.com\/adt\/relations\/source\/definitionBlock"[^>]*href="([^"]+)"/);
- if (defMatch) result.class.definition = parseRange(defMatch[1]);
- const implMatch = xml.match(/rel="http:\/\/www\.sap\.com\/adt\/relations\/source\/implementationBlock"[^>]*href="([^"]+)"/);
- if (implMatch) result.class.implementation = parseRange(implMatch[1]);
- // Parse method elements.
- const methodRe = /<abapsource:objectStructureElement\s+adtcore:type="CLAS\/OM"\s+adtcore:name="([^"]+)"([^>]*)>([\s\S]*?)<\/abapsource:objectStructureElement>/g;
- for (const mm of xml.matchAll(methodRe)) {
- const name = mm[1];
- const attrs = mm[2];
- const inner = mm[3];
- const visibility = attrs.match(/visibility="([^"]+)"/)?.[1];
- const level = attrs.match(/level="([^"]+)"/)?.[1];
- const isAbstract = /abstract="true"/.test(attrs);
- const isConstructor = /constructor="true"/.test(attrs);
- const def = inner.match(/rel="[^"]*\/definitionBlock"\s+href="([^"]+)"/)?.[1];
- const impl = inner.match(/rel="[^"]*\/implementationBlock"\s+href="([^"]+)"/)?.[1];
- result.methods.push({
- name,
- visibility,
- level,
- abstract: isAbstract,
- constructor: isConstructor,
- definition: def ? parseRange(def) : null,
- implementation: impl ? parseRange(impl) : null,
- });
- }
- return result;
- }
- // Splice lines [sr..er] (1-indexed, INCLUSIVE) with replacement text.
- function spliceLines(source, sr, er, replacement) {
- const lines = source.split('\n');
- // Strip trailing \r — PUT must round-trip as the server returns.
- const ret = source.includes('\r\n') ? '\r\n' : '\n';
- const before = lines.slice(0, sr - 1);
- const after = lines.slice(er);
- const replLines = replacement.split('\n');
- const combined = [...before, ...replLines, ...after];
- let out = combined.join('\n');
- // Convert back to source's line endings.
- if (ret === '\r\n' && !out.includes('\r\n')) out = out.replace(/\n/g, '\r\n');
- return out;
- }
- // Insert lines BEFORE line `lineNo` (1-indexed).
- function insertBefore(source, lineNo, text) {
- const lines = source.split('\n');
- const before = lines.slice(0, lineNo - 1);
- const after = lines.slice(lineNo - 1);
- const insertLines = text.split('\n');
- let out = [...before, ...insertLines, ...after].join('\n');
- if (source.includes('\r\n') && !out.includes('\r\n')) out = out.replace(/\n/g, '\r\n');
- return out;
- }
- // ── Per-step harness ──────────────────────────────────────────────────────────
- const results = [];
- async function step(name, fn) {
- const start = Date.now();
- process.stdout.write(`\n── ${name}\n`);
- try {
- const r = await fn();
- const dur = Date.now() - start;
- console.log(` PASS (${dur}ms)`);
- if (r) console.log(` ${typeof r === 'string' ? r : JSON.stringify(r).slice(0, 400)}`);
- results.push({ name, status: 'PASS', dur, detail: r });
- return r;
- } catch (e) {
- const dur = Date.now() - start;
- console.log(` FAIL (${dur}ms): ${e.message}`);
- results.push({ name, status: 'FAIL', dur, error: e.message });
- return null;
- }
- }
- // ── Probe class v1: baseline ──────────────────────────────────────────────────
- const PROBE_V1 = `CLASS ${cfg.className.toLowerCase()} DEFINITION PUBLIC FINAL CREATE PUBLIC.
- PUBLIC SECTION.
- METHODS hello
- IMPORTING name TYPE string
- RETURNING VALUE(result) TYPE string.
- METHODS goodbye
- RETURNING VALUE(result) TYPE string.
- PRIVATE SECTION.
- DATA mv_counter TYPE i.
- ENDCLASS.
- CLASS ${cfg.className.toLowerCase()} IMPLEMENTATION.
- METHOD hello.
- result = |Hello, { name }!|.
- ENDMETHOD.
- METHOD goodbye.
- result = 'Goodbye!'.
- ENDMETHOD.
- ENDCLASS.
- `.replace(/\n/g, '\r\n');
- // ── Main ──────────────────────────────────────────────────────────────────────
- console.log(`Probing ${SYSTEM.toUpperCase()} (${cfg.url}, client=${cfg.client}, user=${cfg.user})`);
- await fetchCsrf();
- console.log(`CSRF acquired`);
- // 0a. Reset: delete then recreate the probe class.
- await step('0a. Delete preexisting probe class (if any)', async () => {
- const deleted = await deleteProbe();
- return deleted ? 'deleted' : 'did not exist';
- });
- await step('0b. Create probe class skeleton', async () => {
- const r = await createProbe();
- return `HTTP ${r.status}`;
- });
- await step('0c. Write v1 source (lock → PUT → unlock → activate)', async () => {
- const { lockHandle, corrNr } = await lockClass();
- try {
- const put = await putMain(PROBE_V1, lockHandle, corrNr);
- if (put.status !== 200) throw new Error(`PUT failed: ${put.status} ${put.text.slice(0, 300)}`);
- } finally {
- await unlockClass(lockHandle);
- }
- const act = await activate();
- if (act.status !== 200) throw new Error(`activate failed: ${act.status} ${act.text.slice(0, 300)}`);
- // Activation can return 200 with embedded errors. Check.
- if (/<chkrun:checkMessage\s/i.test(act.text)) {
- const msg = act.text.match(/shortText="([^"]+)"/)?.[1] ?? '(no shortText)';
- throw new Error(`activation reported errors: ${msg}`);
- }
- return 'activated';
- });
- // 1. Read objectstructure baseline.
- let baseStructure;
- await step('1. GET objectstructure (baseline parse)', async () => {
- const xml = await getObjectStructure();
- baseStructure = parseObjectStructure(xml);
- return {
- classDef: baseStructure.class.definition,
- classImpl: baseStructure.class.implementation,
- methodCount: baseStructure.methods.length,
- methods: baseStructure.methods.map((m) => ({
- name: m.name,
- vis: m.visibility,
- def: m.definition,
- impl: m.implementation,
- })),
- };
- });
- // 2. edit_class_definition happy path: add a method WITH paired impl (no symmetry violation).
- // Caller's intent: add a parameter to the class signature via SDETAIL. We change FINAL→ABSTRACT
- // via DEFINITION only. No method-set change.
- await step('2. edit_class_definition: change to NOT FINAL (no method-set change)', async () => {
- const main = await getMain();
- const oldDef = baseStructure.class.definition;
- const newDef = `CLASS ${cfg.className.toLowerCase()} DEFINITION PUBLIC CREATE PUBLIC.
- PUBLIC SECTION.
- METHODS hello
- IMPORTING name TYPE string
- RETURNING VALUE(result) TYPE string.
- METHODS goodbye
- RETURNING VALUE(result) TYPE string.
- PRIVATE SECTION.
- DATA mv_counter TYPE i.
- ENDCLASS.`.replace(/\n/g, '\r\n');
- const spliced = spliceLines(main, oldDef.sr, oldDef.er, newDef);
- const { lockHandle, corrNr } = await lockClass();
- let put;
- try {
- put = await putMain(spliced, lockHandle, corrNr);
- } finally { await unlockClass(lockHandle); }
- if (put.status !== 200) throw new Error(`PUT failed: ${put.status} ${put.text.slice(0, 300)}`);
- const act = await activate();
- if (act.status !== 200 || /<chkrun:checkMessage\s/i.test(act.text)) {
- throw new Error(`activate failed: ${act.text.slice(0, 300)}`);
- }
- return 'PUT 200, activated';
- });
- // 3. edit_class_definition SAP-side proof: add a method WITHOUT impl stub → write 200, activate fail.
- await step('3. edit_class_definition: refuse-policy SAP-side proof (added METHOD GREET, no stub)', async () => {
- const xml = await getObjectStructure();
- const struct = parseObjectStructure(xml);
- const main = await getMain();
- const oldDef = struct.class.definition;
- const newDef = `CLASS ${cfg.className.toLowerCase()} DEFINITION PUBLIC CREATE PUBLIC.
- PUBLIC SECTION.
- METHODS hello
- IMPORTING name TYPE string
- RETURNING VALUE(result) TYPE string.
- METHODS goodbye
- RETURNING VALUE(result) TYPE string.
- METHODS greet
- IMPORTING who TYPE string
- RETURNING VALUE(result) TYPE string.
- PRIVATE SECTION.
- DATA mv_counter TYPE i.
- ENDCLASS.`.replace(/\n/g, '\r\n');
- const spliced = spliceLines(main, oldDef.sr, oldDef.er, newDef);
- const { lockHandle, corrNr } = await lockClass();
- let put;
- try {
- put = await putMain(spliced, lockHandle, corrNr);
- } finally { await unlockClass(lockHandle); }
- if (put.status !== 200) throw new Error(`PUT unexpectedly failed: ${put.status} ${put.text.slice(0, 300)}`);
- const act = await activate();
- const hasError = act.text.includes('Implementation missing for method "GREET"') || act.text.includes('Implementation missing for method "GREET"');
- if (!hasError) {
- return `WARN: activation didn't reject missing impl as expected. status=${act.status} body=${act.text.slice(0, 300)}`;
- }
- return 'SAP rejected activation as expected (missing impl)';
- });
- // 4. Restore baseline.
- await step('4. Restore baseline (full update v1)', async () => {
- const { lockHandle, corrNr } = await lockClass();
- try {
- const put = await putMain(PROBE_V1, lockHandle, corrNr);
- if (put.status !== 200) throw new Error(`PUT failed: ${put.status}`);
- } finally { await unlockClass(lockHandle); }
- await activate();
- return 'restored';
- });
- // 5. add_method: insert at end of PUBLIC SECTION + add impl stub.
- await step('5. add_method (greet, public) — atomic def+impl insert', async () => {
- const xml = await getObjectStructure();
- const struct = parseObjectStructure(xml);
- // Find last PUBLIC method's definitionBlock end row → insert after.
- const publicMethods = struct.methods.filter((m) => m.visibility === 'public' && m.definition);
- if (publicMethods.length === 0) throw new Error('no public methods to anchor');
- const lastPublicDefEnd = Math.max(...publicMethods.map((m) => m.definition.er));
- const main = await getMain();
- const newDecl = ` METHODS greet
- IMPORTING who TYPE string
- RETURNING VALUE(result) TYPE string.`;
- // Insert AFTER lastPublicDefEnd → before lastPublicDefEnd+1
- let stage1 = insertBefore(main, lastPublicDefEnd + 1, newDecl);
- // Now insert impl stub at end of IMPLEMENTATION block.
- // Need updated impl block range — but we haven't PUT yet; for splicing on the SAME source
- // we can re-parse with abaplint or just use the OLD impl range and add lines INSIDE.
- // Simpler: insert BEFORE the original ENDCLASS of the IMPLEMENTATION block.
- // The class:implementation block ends at struct.class.implementation.er — that's ENDCLASS.
- // After our stage1 splice, the IMPLEMENTATION block has shifted by the number of inserted lines.
- const insertedLines = newDecl.split('\n').length;
- const newImplEnd = struct.class.implementation.er + insertedLines;
- const stub = ` METHOD greet.\n result = ||.\n ENDMETHOD.\n`;
- const stage2 = insertBefore(stage1, newImplEnd, stub);
- const { lockHandle, corrNr } = await lockClass();
- let put;
- try {
- put = await putMain(stage2, lockHandle, corrNr);
- } finally { await unlockClass(lockHandle); }
- if (put.status !== 200) throw new Error(`PUT failed: ${put.status} ${put.text.slice(0, 300)}`);
- const act = await activate();
- if (act.status !== 200 || /<chkrun:checkMessage[^>]*type="E/i.test(act.text)) {
- throw new Error(`activate failed: ${act.text.slice(0, 400)}`);
- }
- return 'PUT 200, activated';
- });
- // 6. edit_method_signature: change greet to take 2 importing params.
- await step('6. edit_method_signature (greet: add greeting param with DEFAULT)', async () => {
- const xml = await getObjectStructure();
- const struct = parseObjectStructure(xml);
- const greet = struct.methods.find((m) => m.name === 'GREET');
- if (!greet?.definition) throw new Error('greet method not found');
- const main = await getMain();
- const newSig = ` METHODS greet
- IMPORTING who TYPE string
- greeting TYPE string DEFAULT 'Hi'
- RETURNING VALUE(result) TYPE string.`;
- const spliced = spliceLines(main, greet.definition.sr, greet.definition.er, newSig);
- const { lockHandle, corrNr } = await lockClass();
- let put;
- try {
- put = await putMain(spliced, lockHandle, corrNr);
- } finally { await unlockClass(lockHandle); }
- if (put.status !== 200) throw new Error(`PUT failed: ${put.status} ${put.text.slice(0, 300)}`);
- const act = await activate();
- if (act.status !== 200 || /<chkrun:checkMessage[^>]*type="E/i.test(act.text)) {
- throw new Error(`activate failed: ${act.text.slice(0, 400)}`);
- }
- return 'PUT 200, activated';
- });
- // 7. delete_method: drop greet (def + impl).
- await step('7. delete_method (greet) — drop both def and impl ranges', async () => {
- const xml = await getObjectStructure();
- const struct = parseObjectStructure(xml);
- const greet = struct.methods.find((m) => m.name === 'GREET');
- if (!greet?.definition || !greet?.implementation) throw new Error('greet ranges missing');
- let main = await getMain();
- // Delete impl FIRST (higher line numbers) so def line numbers stay valid.
- main = spliceLines(main, greet.implementation.sr, greet.implementation.er, '');
- main = spliceLines(main, greet.definition.sr, greet.definition.er, '');
- const { lockHandle, corrNr } = await lockClass();
- let put;
- try {
- put = await putMain(main, lockHandle, corrNr);
- } finally { await unlockClass(lockHandle); }
- if (put.status !== 200) throw new Error(`PUT failed: ${put.status} ${put.text.slice(0, 300)}`);
- const act = await activate();
- if (act.status !== 200 || /<chkrun:checkMessage[^>]*type="E/i.test(act.text)) {
- throw new Error(`activate failed: ${act.text.slice(0, 400)}`);
- }
- return 'PUT 200, activated, greet gone';
- });
- // 8. add_method into missing PROTECTED SECTION — verify refuse-detection input.
- // Probe class currently has only PUBLIC + PRIVATE. add_method protected should refuse.
- await step('8. add_method (protected) — section detection (probe class has no PROTECTED SECTION)', async () => {
- const xml = await getObjectStructure();
- const struct = parseObjectStructure(xml);
- const protectedMethods = struct.methods.filter((m) => m.visibility === 'protected');
- return {
- publicCount: struct.methods.filter((m) => m.visibility === 'public').length,
- protectedCount: protectedMethods.length,
- privateCount: struct.methods.filter((m) => m.visibility === 'private').length,
- attributeCount: 0, // not parsed here
- note: 'plan: refuse if protectedCount === 0 AND no PROTECTED SECTION header exists. Caller adds via edit_class_definition.',
- };
- });
- // 9. Edge case: ABSTRACT class with ABSTRACT methods.
- // Refuse-policy exemption: a method declared ABSTRACT should NOT require an IMPL block,
- // and objectstructure should reflect this (abstract="true", no implementationBlock link).
- const PROBE_ABSTRACT = `CLASS ${cfg.className.toLowerCase()} DEFINITION PUBLIC ABSTRACT CREATE PUBLIC.
- PUBLIC SECTION.
- METHODS hello
- IMPORTING name TYPE string
- RETURNING VALUE(result) TYPE string.
- METHODS to_impl ABSTRACT
- RETURNING VALUE(result) TYPE string.
- ENDCLASS.
- CLASS ${cfg.className.toLowerCase()} IMPLEMENTATION.
- METHOD hello.
- result = |Hello, { name }!|.
- ENDMETHOD.
- ENDCLASS.
- `.replace(/\n/g, '\r\n');
- await step('9. Edge: ABSTRACT class with ABSTRACT method — refuse-policy exemption check', async () => {
- // Rewrite the class with an abstract method.
- const { lockHandle, corrNr } = await lockClass();
- try {
- const put = await putMain(PROBE_ABSTRACT, lockHandle, corrNr);
- if (put.status !== 200) throw new Error(`PUT failed: ${put.status} ${put.text.slice(0, 300)}`);
- } finally { await unlockClass(lockHandle); }
- const act = await activate();
- if (act.status !== 200 || /<chkrun:checkMessage[^>]*type="E/i.test(act.text)) {
- throw new Error(`activate failed: ${act.text.slice(0, 400)}`);
- }
- const xml = await getObjectStructure();
- const struct = parseObjectStructure(xml);
- const abs = struct.methods.find((m) => m.name === 'TO_IMPL');
- return {
- abstractMethodFound: !!abs,
- abstract: abs?.abstract,
- hasDefinition: !!abs?.definition,
- hasImplementation: !!abs?.implementation,
- expected: 'abstract=true, no implementation link',
- };
- });
- // 10. Edge case: 3-section class — add_method works in PROTECTED when section exists.
- const PROBE_3SECTIONS = `CLASS ${cfg.className.toLowerCase()} DEFINITION PUBLIC CREATE PUBLIC.
- PUBLIC SECTION.
- METHODS pub_a RETURNING VALUE(r) TYPE string.
- PROTECTED SECTION.
- METHODS prot_a RETURNING VALUE(r) TYPE string.
- PRIVATE SECTION.
- METHODS priv_a RETURNING VALUE(r) TYPE string.
- ENDCLASS.
- CLASS ${cfg.className.toLowerCase()} IMPLEMENTATION.
- METHOD pub_a.
- r = 'pub'.
- ENDMETHOD.
- METHOD prot_a.
- r = 'prot'.
- ENDMETHOD.
- METHOD priv_a.
- r = 'priv'.
- ENDMETHOD.
- ENDCLASS.
- `.replace(/\n/g, '\r\n');
- await step('10. Edge: 3-section class — add_method into PROTECTED SECTION', async () => {
- const { lockHandle: lh1, corrNr: cn1 } = await lockClass();
- try { await putMain(PROBE_3SECTIONS, lh1, cn1); } finally { await unlockClass(lh1); }
- await activate();
- const xml = await getObjectStructure();
- const struct = parseObjectStructure(xml);
- const protMethods = struct.methods.filter((m) => m.visibility === 'protected' && m.definition);
- if (protMethods.length === 0) throw new Error('no protected methods to anchor');
- const lastProtEnd = Math.max(...protMethods.map((m) => m.definition.er));
- const main = await getMain();
- const newDecl = ` METHODS prot_b RETURNING VALUE(r) TYPE string.`;
- let stage1 = insertBefore(main, lastProtEnd + 1, newDecl);
- const insertedLines = newDecl.split('\n').length;
- const newImplEnd = struct.class.implementation.er + insertedLines;
- const stub = ` METHOD prot_b.\n r = 'b'.\n ENDMETHOD.\n`;
- const stage2 = insertBefore(stage1, newImplEnd, stub);
- const { lockHandle: lh2, corrNr: cn2 } = await lockClass();
- let put;
- try { put = await putMain(stage2, lh2, cn2); } finally { await unlockClass(lh2); }
- if (put.status !== 200) throw new Error(`PUT failed: ${put.status} ${put.text.slice(0, 300)}`);
- const act = await activate();
- if (act.status !== 200 || /<chkrun:checkMessage[^>]*type="E/i.test(act.text)) {
- throw new Error(`activate failed: ${act.text.slice(0, 400)}`);
- }
- // Re-fetch structure to confirm.
- const xml2 = await getObjectStructure();
- const struct2 = parseObjectStructure(xml2);
- return {
- protectedMethodsAfter: struct2.methods.filter((m) => m.visibility === 'protected').map((m) => m.name),
- };
- });
- // 11. Edge case: empty class skeleton — can add_method work into a freshly-created class?
- const PROBE_SKELETON = `CLASS ${cfg.className.toLowerCase()} DEFINITION PUBLIC FINAL CREATE PUBLIC.
- PUBLIC SECTION.
- PROTECTED SECTION.
- PRIVATE SECTION.
- ENDCLASS.
- CLASS ${cfg.className.toLowerCase()} IMPLEMENTATION.
- ENDCLASS.
- `.replace(/\n/g, '\r\n');
- await step('11. Edge: empty class skeleton — add_method into a class with no existing methods', async () => {
- const { lockHandle: lh1, corrNr: cn1 } = await lockClass();
- try { await putMain(PROBE_SKELETON, lh1, cn1); } finally { await unlockClass(lh1); }
- await activate();
- const xml = await getObjectStructure();
- const struct = parseObjectStructure(xml);
- // No existing methods → insertion anchor is the end of the PUBLIC SECTION line.
- // We can't get that from objectstructure (no method to anchor against).
- // Plan: when method-set is empty, the implementation must fall back to scanning the
- // DEFINITION block for "PUBLIC SECTION." line and inserting AFTER it.
- // Here we simulate by string-searching the source.
- const main = await getMain();
- const lines = main.split(/\r?\n/);
- const publicSectionLine = lines.findIndex((l) => /^\s*PUBLIC\s+SECTION\s*\.\s*$/i.test(l));
- if (publicSectionLine < 0) throw new Error('no PUBLIC SECTION line found');
- const newDecl = ` METHODS first RETURNING VALUE(r) TYPE string.`;
- const stage1 = insertBefore(main, publicSectionLine + 2, newDecl);
- const insertedLines = newDecl.split('\n').length;
- const newImplEnd = struct.class.implementation.er + insertedLines;
- const stub = ` METHOD first.\n r = '1'.\n ENDMETHOD.\n`;
- const stage2 = insertBefore(stage1, newImplEnd, stub);
- const { lockHandle: lh2, corrNr: cn2 } = await lockClass();
- let put;
- try { put = await putMain(stage2, lh2, cn2); } finally { await unlockClass(lh2); }
- if (put.status !== 200) throw new Error(`PUT failed: ${put.status} ${put.text.slice(0, 300)}`);
- const act = await activate();
- if (act.status !== 200 || /<chkrun:checkMessage[^>]*type="E/i.test(act.text)) {
- throw new Error(`activate failed: ${act.text.slice(0, 400)}`);
- }
- return 'add_method into empty class works — requires string fallback for section anchor';
- });
- // 12. Restore baseline.
- await step('12. Restore baseline', async () => {
- const { lockHandle, corrNr } = await lockClass();
- try { await putMain(PROBE_V1, lockHandle, corrNr); } finally { await unlockClass(lockHandle); }
- await activate();
- return 'restored';
- });
- // 10. Summary
- console.log('\n══ Summary ══');
- for (const r of results) {
- console.log(` ${r.status.padEnd(4)} ${r.name}`);
- if (r.error) console.log(` ${r.error}`);
- }
- const failed = results.filter((r) => r.status === 'FAIL').length;
- console.log(`\n${failed === 0 ? 'ALL PASSED' : `${failed} FAILED`}`);
- process.exit(failed === 0 ? 0 : 1);
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.