diff --git a/apex/SKILL.md b/apex/SKILL.md index fd9e13d..45f928b 100644 --- a/apex/SKILL.md +++ b/apex/SKILL.md @@ -1,11 +1,11 @@ --- name: apex -description: Oracle APEX skills for Oracle APEX application development. +description: Oracle APEX skills for application generation, APEX administration, workspace lifecycle, deployment safety, monitoring, and security guardrails. --- -# APEXLang Skills +# Oracle APEX Skills -This domain contains Oracle APEX skills for Oracle APEX application development. +This domain contains Oracle APEX skills for application generation and APEX administration. ## How to Use This Domain @@ -16,18 +16,25 @@ This domain contains Oracle APEX skills for Oracle APEX application development. ```text apex/ +├── admin/ ├── apexlang/ ``` ## Category Routing -| Topic | Directory | -| ----------------------------------------- | --------------- | -| Generate APEX applications using APEXlang | `apex/apexlang` | +| Topic | Directory | +| --------------------------------------------------------------------- | --------------- | +| Generate, validate, or materially change APEX applications using APEXlang | `apex/apexlang` | +| Administer APEX workspaces, users, schema mappings, deployments, monitoring, and security guardrails | `apex/admin` | +| Create, reset, unlock, or bootstrap an APEX Instance Administrator for INTERNAL/APEX Administration Services | `apex/admin` | ## Key Starting Points +- `apex/admin/SKILL.md` +- `apex/admin/references/deployment/instance-admin-bootstrap.md` +- `apex/admin/references/workspace/lifecycle.md` +- `apex/admin/references/workspace/users-and-auth.md` - `apex/apexlang/references/workflows/apex-generation.md` -- `apex/apexlang/references/domains/README.md` \ No newline at end of file +- `apex/apexlang/references/domains/README.md` diff --git a/apex/admin/SKILL.md b/apex/admin/SKILL.md new file mode 100644 index 0000000..24e4636 --- /dev/null +++ b/apex/admin/SKILL.md @@ -0,0 +1,217 @@ +--- +name: admin +description: Oracle APEX administration workflows for workspace lifecycle, provisioning, users, schema mapping, deployment, monitoring, security guardrails, and source-backed operational checks. Use when Codex needs APEX admin guidance, APEX workspace operations, APEX deployment/import review, APEX runtime monitoring, or APEX-specific safety handling. +--- + +# Oracle APEX Admin + +Use this skill for APEX administration. Load only the routed reference needed for the request, then add a second reference only when the workflow crosses that boundary. + +## Structure + +```text +admin/ +├── SKILL.md +├── references/ +│ ├── debugging/ +│ ├── deployment/ +│ ├── monitoring/ +│ ├── security/ +│ └── workspace/ +├── tools/ +│ ├── apex-export-risk-scan.mjs +│ └── workspace-admin-plan.mjs +``` + +## Token Use + +- Load one routed reference first; add another only when the user request spans categories. +- Use `rg` or section search for exact checks instead of reading whole reference directories. +- Load `references/security/safety-messages.md` only when an exact user-facing safety message is needed. +- For SQL examples, prefer the smallest relevant snippet from the reference file. +- Treat large customer artifacts as local files, not context. For APEX exports, AWR/ASH reports, HAR files, logs, debug dumps, screenshots, and console output, first identify the relevant sections with local search, parser, or tool output, then load or quote only the smallest necessary excerpt. +- Use the operation protocol file as the running compact memory for long investigations. Append short redacted status updates there and refer to that file path instead of repeating full evidence, browser observations, SQL results, or prior reasoning in every response. +- Keep cache-friendly stable context: prefer file paths, section names, query labels, and concise summaries over repeatedly pasting unchanged reference text or raw artifacts. +- For live SQL checks, prefer metadata/count/top-N queries and explicit column lists. Avoid `SELECT *`, payload CLOB/BLOB columns, debug message bodies, request bodies, or item values unless explicitly needed and confirmed. +- For browser debugging, capture request metadata, timing, status, page/action IDs, and visible symptoms; do not paste full DOM, HAR, console dumps, screenshots, or network payloads into chat. +- Use `tools/` only for generic APEX-admin analysis or planning. Tools must not contain customer-specific paths, customer exports, SQLcl automation, ORDS tuning, or database administration logic. +- Customer cases may inform generic skill improvements, but never add customer names, customer paths, export filenames, application names, domains, users, line references, findings, or incident details to skill files, tools, tests, references, examples, or committed docs. + +## Analysis Output Handling + +- Before starting any static or file-only review that does not need database access, explicitly tell the user that no database connection or live MCP database access will be used. Keep it short, for example: "I can analyze this export statically; no database access is needed for this step." +- If database access is not available and the request may depend on APEX version, ask the user which APEX version is used before making version-sensitive recommendations. If the user does not know, continue only with version-tolerant static analysis using APEX 26.1 documentation as the default reference and state that final API/view/column checks must be verified later against the target instance. +- If a static review later needs live APEX evidence, stop before connecting and apply the APEX Admin Identity Gate. If it needs generic DB evidence, stop before handoff and ask whether to switch to the relevant DB skill. +- For any customer-specific APEX application analysis request whose entry point is a `.sql` or `.apx` APEX application export, the first user-facing response must include the additional-evidence intake question before any scan, static review, findings, or report drafting starts. Ask whether the user has APEX Activity Log/Page Performance, APEX Debug, HAR/Network, AWR/ASH, SQL Monitor, ORDS logs, deployment logs, or another export for the same case. You may combine this with the no-database-access notice and the output-location question. If the user already explicitly declined more evidence in the same prompt, proceed and state the evidence limit. +- When the entry point is a customer-specific APEX application export file, including `.sql` or `.apx`, route first to `references/monitoring/apex-performance-evidence.md` before any export-only review. Ask once whether more customer evidence exists for the same case, including APEX Activity Log/Page Performance, APEX Debug, HAR/Network, AWR/ASH, SQL Monitor, ORDS logs, deployment logs, or another export. If the user declines or has no more files, continue with the export and state the evidence limits. +- Before substantive analysis of customer-specific performance, runtime, deployment, or incident evidence, ask once whether the user has more relevant customer evidence for the same case, such as APEX Activity Log/Page Performance, APEX Debug, HAR/Network, AWR/ASH, SQL Monitor, ORDS logs, deployment logs, or another APEX export. Treat this as an intake question, not a requirement: if the user declines or no more files are available, proceed with the available evidence, finish the analysis, and state the evidence limits. +- When the user provides customer-specific files or evidence and asks for analysis, ask before substantive analysis whether the result should be chat-only or saved as an external artifact. If saved, require a user-confirmed output directory or exact file path before continuing. +- For every substantive live APEX admin workflow, state-changing workflow, customer-evidence analysis, or debugging workflow, load `references/debugging/protocol-file.md` and create or update a local operation protocol file outside the skill tree. Debugging includes APEX Debug/Trace, Activity Log/Page Performance review, error-log analysis, Session Replay, HAR/network/console review, and browser-guided debugging through Codex or another browser-capable tool. +- Before starting debugging or any state-changing APEX admin work, require a user-confirmed protocol output directory or exact file path. If the user gives a directory, use a timestamped Markdown filename such as `apex-admin-protocol-YYYYMMDD-HHMMSS.md` or `apex-debug-protocol-YYYYMMDD-HHMMSS.md`. If no path is provided, ask for it before continuing. +- The protocol file must record the local date/time and timezone, environment classification, target workspace/application/page/user/time window when known, active database identity or browser-session identity category, confirmation gates, actions taken, observations, evidence references, handoffs, and final status. Redact secrets, cookies, tokens, authorization headers, passwords, request bodies, item values, and unnecessary personal data. +- Skill protocol and logging output must be local files only. Do not create database tables, log tables, runtime tables, triggers, packages, or instrumentation objects for APEX admin skill logging in an APEX schema, parsing schema, workspace schema, or customer application schema. +- Do not write customer-specific analysis output into this skill, the repository, `tools/`, `references/`, examples, tests, or committed documentation unless the user explicitly asks for a generic, sanitized skill improvement instead. +- Do not create customer-specific output folders such as `apex/admin/`. Customer reports, logs, generated checklists, and derived artifacts must go to a user-confirmed external path outside the skill tree. +- If the user gives a source file path but no output path, do not infer that the result belongs beside the source. Ask for the output directory or exact file path first. +- When the user gives a directory, create or update only the requested result file inside that directory. When the user gives a file path, use that exact file path after confirming overwrite if the file already exists. +- Keep customer identifiers, application names, source paths, export filenames, line references, and findings only in the confirmed external output artifact and chat summary; never copy them into skill files. + +## Routing + +- Workspace lifecycle/provisioning/listing/removal: `references/workspace/instance-admin-api.md`, `references/workspace/lifecycle.md`, `references/workspace/resource-governance.md`, `references/workspace/users-and-auth.md`, `references/workspace/schema-mapping.md`, `references/workspace/removal.md`, `references/workspace/version-notes.md`, `references/workspace/security-review.md` +- Security/auth/session/export safety: `references/security/guardrails.md`, `references/security/safety-messages.md`, `references/security/audit-columns.md`, `references/security/security-review.md` +- Debugging/reproduction/protocol files: `references/debugging/protocol-file.md`, `references/debugging/live-browser-debugging.md` +- Monitoring/runtime diagnosis/MCP availability: start broad APEX performance cases and customer-specific `.sql` or `.apx` APEX application export analysis with `references/monitoring/apex-performance-evidence.md`; then route to `references/monitoring/workspace-monitor-activity.md`, `references/monitoring/activity-log.md`, `references/monitoring/error-handling.md`, `references/monitoring/instance-debug-api.md`, `references/monitoring/user-journey-replay.md`, `references/monitoring/background-jobs.md`, `references/monitoring/rest-data-sources.md`, `references/monitoring/ai-token-monitoring.md`, `references/monitoring/page-performance.md`, `references/monitoring/export-runtime-risk-review.md`, `references/monitoring/ir-ig-tuning.md`, `references/monitoring/awr-wait-correlation.md`, `references/monitoring/mcp-availability.md`, `references/monitoring/security-review.md` +- Deployment/export/import/patching/instance-administrator bootstrap: `references/deployment/pre-check.md`, `references/deployment/export-review.md`, `references/deployment/import-promotion.md`, `references/deployment/deployment-identity.md`, `references/deployment/instance-admin-bootstrap.md`, `references/deployment/post-deploy-validation.md`, `references/deployment/patching.md`, `references/deployment/security-review.md` +- New APEX application generation: announce the skill handoff, then route the application-generation work to `apex/apexlang/SKILL.md`. Keep `admin/` loaded only for workspace, deployment identity, connection safety, import/promotion, monitoring, and post-deploy validation context. + +## Prompt Interpretation + +- Treat "APEX instance admin", "APEX instance administrator", "APEX internal admin", "admin for INTERNAL", "INTERNAL workspace admin", and "APEX Administration Services admin" as requests for an APEX Instance Administrator unless the user explicitly says they mean a database account or role grant. +- For those prompts, load `references/deployment/instance-admin-bootstrap.md` first. Do not ask whether the user means a database account with `APEX_ADMINISTRATOR_ROLE`; that role is for routine instance-level APEX API automation, not the initial APEX Administration Services administrator bootstrap. +- If the user later clarifies "an APEX internal/admin user for the INTERNAL workspace", switch immediately to the `apxchpwd.sql` bootstrap path. Do not block on an active `SYS` or `SYSTEM` connection, and do not request a saved non-SYS/SYSTEM SQLcl MCP connection for the password-setting step. +- Ask only for details needed to tailor the runbook: self-managed/container versus managed service, target PDB/service name, APEX installation directory containing `apxchpwd.sql`, username, and email. Never ask for the password in chat. If the environment is Autonomous AI Database or Oracle APEX AI Application Generator Service (APEX Service), do not provide `apxchpwd.sql` run commands; route to the service-specific administration/reset path instead. +- Before giving final privileged bootstrap commands or saying the user can proceed, summarize the interpreted intent and all non-secret target details, then require explicit user confirmation. Do not proceed from inferred values, remembered context, or partial confirmation. + +## Skill Handoff + +When a user asks to create, scaffold, generate, or materially change an APEX application rather than only create or administer a workspace, stop before generating the application and emit this handoff message: + +```text +APEXlang skill in use: apex/apexlang/SKILL.md for APEX application generation. The APEX admin skill is being used only for workspace, deployment identity, connection safety, and post-deploy validation. +``` + +Before MCP-backed application creation, import, or materialization continues, apply the APEX Admin Identity Gate below. Do not continue only because the user accepts the currently connected database user; the user must confirm that the connection is the intended APEX admin identity. + +## APEX Admin Identity Gate + +All live MCP-backed work owned by this skill must run only under a confirmed APEX admin identity. Static file review of APEX exports, AWR/ASH reports, HAR files, CSV extracts, and logs does not require a database connection. + +Accepted APEX admin identities: + +- A dedicated non-`SYS`/`SYSTEM` database account granted `APEX_ADMINISTRATOR_ROLE` for instance-level APEX administration. +- On Autonomous Database or APEX Service only, the service `ADMIN` account when the user explicitly confirms that it is the environment's APEX administration identity and the work remains APEX-admin-scoped. +- `SYSTEM` without `SYSDBA` only when the user explicitly accepts the privileged APEX-admin-scoped session by replying exactly `YES` in uppercase after seeing the verified identity, action scope, target objects, password-handling path when relevant, and risk summary. + +Before any live APEX query, APEX API call, import, workspace operation, monitoring-query, debug-log query, or version check through MCP, verify and show the active identity: + +```sql +SELECT SYS_CONTEXT('USERENV','SESSION_USER') AS session_user, + SYS_CONTEXT('USERENV','CURRENT_USER') AS current_user, + SYS_CONTEXT('USERENV','ISDBA') AS is_dba +FROM dual; +``` + +If permissions allow, also verify `APEX_ADMINISTRATOR_ROLE` through `SESSION_ROLES` or `USER_ROLE_PRIVS`. + +Stop the APEX admin workflow when the active identity is `SYS`, `ISDBA = TRUE`, an app parsing schema, a workspace developer/end-user, an ORDS/APEX runtime account, a generic deployment user, or unknown. Ask for the confirmed APEX admin connection before continuing. This applies to read-only APEX evidence gathering as well as change operations. + +Before workspace creation or other state-changing APEX admin work, prefer a dedicated non-`SYS`/`SYSTEM` account with `APEX_ADMINISTRATOR_ROLE`. If no such account is available or the role/account cannot be verified, stop and give the user two explicit choices: + +1. Use `SYSTEM` without `SYSDBA` once to create or repair the dedicated APEX admin account/role setup, then reconnect as that dedicated account. +2. Continue the current APEX-admin-scoped workflow as `SYSTEM` without `SYSDBA`. + +Both choices require `SESSION_USER = SYSTEM`, `CURRENT_USER = SYSTEM`, `ISDBA = FALSE`, a visible scope/risk/password-handling summary, and a fresh user reply of exactly `YES` in uppercase before any MCP-backed SQL or APEX API call. Do not create a look-alike `APEX_ADMINISTRATOR_ROLE` silently. If the installed APEX environment does not expose the expected role or package privileges, state that as an installation/privilege repair concern and require explicit `SYSTEM` confirmation before any repair plan. + +`SYSTEM` is a privileged exception, not the default recommendation. When a confirmed least-privilege APEX admin account is unavailable or the user intentionally chooses `SYSTEM`, allow `SYSTEM` to perform APEX-admin-scoped work, including creating an APEX admin database account, granting `APEX_ADMINISTRATOR_ROLE`, workspace lifecycle operations, APEX workspace-user administration, imports, monitoring queries, debug-log queries, and supported APEX API automation. Require all of the following before continuing: `SESSION_USER = SYSTEM`, `CURRENT_USER = SYSTEM`, `ISDBA = FALSE`, a visible scope/risk summary, and a fresh user reply of exactly `YES` in uppercase. Do not accept `yes`, `Yes`, partial confirmation, remembered context, or implied consent. Do not put passwords in chat, scripts, SQL text, or logged MCP tool calls; if password-based account creation is required, provide local SQLcl steps with placeholders or ask the user to run the password step outside logged MCP execution. + +For password handling, do not ask the user to paste a password into chat and do not generate a password through logged MCP/tool output. Offer one of these safe paths instead: the user enters the password only at an interactive local SQLcl prompt, the user supplies a placeholder-backed local secret outside chat, or the user runs a local password-generator command themselves and enters the generated password only at the password prompt. If a generated strong password is desired, provide the command for the user to run locally rather than printing the generated secret in chat. + +The APEX Instance Administrator bootstrap path in `references/deployment/instance-admin-bootstrap.md` is the only documented exception, because Oracle's `apxchpwd.sql` flow can require `SYS AS SYSDBA`. That exception is not a routine MCP APEX admin session and must not be used for workspace creation, imports, monitoring, or APEX API automation. + +## Supported Version Gate + +Before any MCP-backed APEX admin workflow, check the installed APEX version from `APEX_RELEASE`. Continue only for APEX releases supported by this skill: `26.1`, `24.2`, and `24.1` as of June 2026. If the detected version is not supported, emit the unsupported-version safety message and stop before generating SQL, PL/SQL, deployment steps, monitoring queries, or workspace changes. + +Use `references/workspace/version-notes.md` for the exact gate query and version-sensitive follow-up checks. + +## Tools + +- Static APEX export risk scan: + +```bash +node apex/admin/tools/apex-export-risk-scan.mjs --export --format markdown +``` + +- Workspace admin checklist and supported APEX snippets: + +```bash +node apex/admin/tools/workspace-admin-plan.mjs --action inventory --workspace +``` + +The tools are optional accelerators. They do not replace reading the routed reference, and they must not execute ORDS, SQLcl, or generic database administration work. + +## Scope + +Keep this skill APEX-admin-specific. Before adding or expanding guidance, check whether the generic database topic is already covered under `db/`. + +Use this skill for APEX workspaces, application administration metadata, App Builder admin behavior, runtime behavior, session state, APEX activity/debug logs, APEX users, Team Development, supported public `APEX_*` views, and APEX APIs such as `APEX_UTIL`, `APEX_INSTANCE_ADMIN`, `APEX_INSTANCE_DEBUG`, and `APEX_APPLICATION_INSTALL`. Treat public `APEX_*` views and documented APEX APIs as the supported administration contract; do not query or update internal APEX repository tables as a shortcut. Do not create or alter APEX internal/runtime tables, application tables, logging tables, or customer-owned database objects from this skill. Do not use this skill to generate new APEX application artifacts; hand that work to `apex/apexlang`. + +This skill owns only the APEX side of the work. It may identify APEX evidence that explains runtime symptoms, but it must not tune ORDS pools, run SQLcl workflows, design database indexes, interpret generic wait events, or perform database administration as part of this skill. + +For new database users/schemas that will be used as APEX workspace or parsing schemas, apply the standard APEX schema privileges from `APEX_GRANTS_FOR_NEW_USERS_ROLE` through APEX-managed APIs when supported. Use `APEX_INSTANCE_ADMIN.ADD_SCHEMA(..., p_grant_apex_privileges => TRUE)` as the default for schema-to-workspace mappings that are not already mapped. This is an APEX administration API option and may be used under the confirmed APEX admin identity. Do not generate manual `GRANT` or `REVOKE` statements from this skill; route manual privilege remediation to `db/security/privilege-management.md`. + +Do not duplicate generic database guidance. Privilege management, auditing, encryption, network security, data masking, VPD/RLS, AWR, ASH, wait events, SQL tuning, SQLcl basics, and ORDS fundamentals are outside the APEX admin skill scope. Mention them only as external handoff topics when APEX evidence points beyond APEX. + +When using a generic DB skill, announce it with `DB skill in use: db/...`, for example: + +```text +DB skill in use: db/performance/wait-events.md for the generic wait-event analysis. The APEX admin skill is being used for APEX activity-log correlation. +``` + +If the user attaches or references an AWR report, ASH extract, SQL Monitor report, execution plan, wait-event output, `V$`/`DBA_HIST` evidence, or ORDS pool/runtime diagnostics during APEX monitoring work, stop before interpreting that evidence. Ask whether to switch to the relevant DB skill, and continue only after the user confirms. After handoff, follow the selected DB skill's identity and connection requirements: use a diagnostics/performance account for AWR, ASH, `DBA_HIST`, `V$`, SQL Monitor, and execution-plan evidence; a DB admin or privilege-management identity for users, grants, quotas, and schemas; and an ORDS/runtime administration identity for ORDS pool or gateway diagnostics. Do not silently reuse the APEX admin connection for DB-skill work unless the DB skill's own rules explicitly accept that identity. + +## Safety + +- Use least privilege for parsing schemas, workspace users, database-login users, and automation accounts. Do not recommend broad grants such as `DBA`, `SYSDBA`, `SELECT ANY TABLE`, `EXECUTE ANY PROCEDURE`, `CREATE ANY TABLE`, `GRANT ANY ROLE`, `GRANT ANY PRIVILEGE`, or `WITH ADMIN OPTION` unless the user explicitly asks for privileged administration and the risk is called out. +- Do not connect MCP or routine automation as `SYS`, `SYSDBA`, parsing schemas, workspace developers, end users, ORDS/APEX runtime accounts, or generic deployment users for APEX admin work. Use only a confirmed APEX admin identity as defined in the APEX Admin Identity Gate. `SYSTEM` is allowed only after the exact uppercase `YES` confirmation required by that gate. +- If the user asks to create, reset, unlock, or bootstrap an APEX Instance Administrator for APEX Administration Services or the `INTERNAL` workspace, route to `references/deployment/instance-admin-bootstrap.md`. Do not treat this as a normal workspace user created with `APEX_UTIL.CREATE_USER`, and do not ask for a least-privilege `APEX_ADMINISTRATOR_ROLE` connection as the primary path. First confirm whether the environment is self-managed/container/co-managed Cloud or a fully managed service. For new self-managed/container/co-managed Cloud installations, the supported path is running `apxchpwd.sql` from the APEX installation directory as `SYS AS SYSDBA` in the database where APEX is installed. For Autonomous AI Database or Oracle APEX AI Application Generator Service (APEX Service), do not provide local script steps; direct the user to the service-specific administration/reset path. +- Do not run `apxchpwd.sql` through `sql_run`, and do not put the Instance Administrator password in chat, SQL, scripts, or logged MCP tool calls. Give the user a terminal/SQLcl command sequence with placeholders and tell them to enter the password only at the script prompt. +- For APEX Instance Administrator bootstrap, always require an explicit confirmation of the action, environment type, target PDB/service, APEX installation directory, username, and email before giving final run commands or instructing the user to execute them. +- Before MCP-backed APEX admin work, apply the APEX Admin Identity Gate. If the identity is not a confirmed APEX admin identity, stop and ask for the correct APEX admin connection. +- If the workflow needs generic database administration or diagnostics such as non-APEX database users/schemas, manual grants, quotas, tablespaces, ORDS configuration, AWR, ASH, `V$SESSION`, `V$SQL`, wait events, or system-level diagnostics, stop the APEX admin workflow, announce the DB skill handoff, and ask for the connection/user required by that DB skill. The `SYSTEM` exception in this skill covers only APEX-admin-scoped work after exact uppercase `YES` confirmation; it is not permission to take over generic DB/ORDS/performance work. +- Before MCP-backed APEX admin work, check `APEX_RELEASE.VERSION_NO` against the supported-version gate. If the version is unsupported, stop and do not generate version-sensitive SQL or change steps. +- Before MCP-backed APEX application creation, scaffold materialization, or import/promotion work, show the verified `SESSION_USER`, `CURRENT_USER`, and `ISDBA` values and continue only after the user confirms that the identity is the intended APEX admin identity. +- Keep APEX security contexts separate: workspace administrator, developer, end user, parsing schema, database-login user, ORDS/APEX runtime account, and DBA/admin account are different roles. +- Do not treat APEX parsing schemas as personal interactive logins in production. +- Prefer supported public `APEX_*` views and documented APEX APIs. Do not query or write directly to internal APEX repository tables. Keep live queries scoped to the relevant workspace, application, page, session, user, and time window whenever that context is known. +- Do not create, alter, or drop database objects for skill logging, debugging protocols, audit metadata, token instrumentation, or application instrumentation. If persistent application instrumentation is requested, stop and route to the owning APEXlang or DB skill. Writing to an existing customer-owned table is also state-changing and requires explicit user confirmation in the owning skill. +- Treat versions and managed environments as variable. Inspect availability with `APEX_RELEASE`, `APEX_DICTIONARY`, `ALL_TAB_COLUMNS`, `ALL_ARGUMENTS`, or `DESC` before relying on version-specific columns or package signatures. +- Protect destructive actions with object listings, fresh exact English confirmation prompts, protected-account checks, and no remembered-context assumptions. Workspace-related database users may be dropped only when the user explicitly asks to remove the workspace and its listed related database users/components and confirms that this is their own will. Load `references/workspace/removal.md`. +- After interrupted APEX provisioning, reconnect, inventory each planned artifact individually, and ask whether to roll back only the listed artifacts before retrying or continuing. Load `references/monitoring/mcp-availability.md` and `references/workspace/lifecycle.md`. +- Before APEX workflows that use MCP database access, run the APEX MCP availability guard. If MCP reports `Transport closed` or an unavailable tool channel, stop and do not continue from stale database state. +- Never include real secrets in skills, examples, logs, exports, or chat output. +- Treat APEX activity logs, debug logs, error messages, request values, Team Development files, exports, and session context as potentially sensitive. +- Do not treat APEX session state, hidden items, read-only items, or client-side checks as a security boundary. +- For tenant isolation or sensitive row access, APEX authorization can help the UI, but critical data isolation belongs in the database. Hand off implementation details to `db/security/row-level-security.md`. +- APEX exports may contain application logic, URLs, authorization schemes, build options, static files, credential references, defaults, and other sensitive metadata. +- For APEX-owned application tables, the admin skill may review existing audit metadata such as created/updated timestamp and user columns. It must not add audit columns or triggers. For implementation or database auditing, announce and use the owning APEXlang or DB skill. +- Mark licensed features and production constraints, especially AWR/ASH/Diagnostics Pack and database security options whose licensing depends on deployment. +- End substantial APEX admin skill additions with a security review covering privileges, secrets, auditability, data exposure, version/cloud restrictions, and destructive actions. For security-sensitive reviews or debugging, summarize which checks were performed, which checks were not performed, and which items were handed off to DB/ORDS/APEXlang instead of silently leaving gaps. + +## Documentation + +Use official Oracle APEX documentation only. + +Primary APEX 26.1 entry points: + +```text +https://docs.oracle.com/en/database/oracle/apex/26.1/htmrn/ +https://docs.oracle.com/en/database/oracle/apex/26.1/htmig/ +https://docs.oracle.com/en/database/oracle/apex/26.1/aeapi/ +``` + +Current APEX support status: + +```text +https://www.oracle.com/apex/ +``` + +Secondary supported entry points when the installed or target environment is APEX 24.2 or APEX 24.1: + +```text +https://docs.oracle.com/en/database/oracle/apex/24.2/ +https://docs.oracle.com/en/database/oracle/apex/24.1/ +``` + +Do not use APEX documentation older than 24.1 unless the user explicitly asks for legacy-version migration or compatibility analysis. If legacy documentation is needed, label it as legacy and keep the current 26.1 entry point visible. diff --git a/apex/admin/references/debugging/live-browser-debugging.md b/apex/admin/references/debugging/live-browser-debugging.md new file mode 100644 index 0000000..dc2ddaa --- /dev/null +++ b/apex/admin/references/debugging/live-browser-debugging.md @@ -0,0 +1,135 @@ +# Live Browser Debugging + +Use this reference when the user has an APEX application or App Builder session open in a browser-capable tool and wants the agent to reproduce, observe, or narrow an APEX issue interactively. + +This is browser/UI-assisted APEX debugging. It does not replace the APEX Admin Identity Gate for MCP/SQL, and it does not own generic database, ORDS, SQL tuning, or APEX application artifact changes. + +## Boundary + +This reference owns: + +- Reproducing an issue in an already authenticated APEX browser session. +- Inspecting visible page behavior, screenshots, DOM state, browser console output, and network request metadata when the browser tool exposes them. +- Distinguishing page load, submit, AJAX, REST, static asset, and client-side JavaScript symptoms. +- Capturing correlation facts that can later be matched with APEX Activity Log, Page Performance, Debug, or Error evidence. + +This reference does not own: + +- APEX Debug/Trace policy, retention, or SQL-backed report queries. Use `../monitoring/workspace-monitor-activity.md`, `../monitoring/activity-log.md`, `../monitoring/page-performance.md`, and `../monitoring/error-handling.md`. +- Session Replay or SQL-backed journey reconstruction. Use `../monitoring/user-journey-replay.md`. +- Static export risk review. Use `../monitoring/export-runtime-risk-review.md`. +- MCP/database availability decisions. Use `../monitoring/mcp-availability.md`. +- AWR, ASH, SQL Monitor, wait events, execution plans, ORDS pool diagnostics, users, grants, quotas, tablespaces, or schema changes. Route to the relevant DB/ORDS skill. +- Generating or materially changing APEX application artifacts. Route to `apex/apexlang/SKILL.md`. + +## Browser Tool Capability Contract + +Any browser-guided tool may use this workflow when it can inspect at least one of: + +- the current APEX page visually through screenshots or viewport state; +- clickable UI state and navigation path; +- browser console messages; +- network request metadata such as URL path, method, status, timing, request type, and response size. + +If the tool cannot access console or network details, limit findings to visible behavior and ask the user for exported browser evidence such as a redacted HAR or screenshot. If the tool cannot attach to the authenticated session, ask the user to sign in manually or provide static evidence; do not ask for credentials in chat. + +## Browser Session User + +Pure browser inspection does not require a database user. The user signs in to APEX manually in the browser, and the agent uses only the already authenticated browser session. Do not ask for APEX passwords, cookies, session IDs, bearer tokens, or browser profile secrets in chat. + +Use the least privileged browser identity that can reproduce or inspect the issue: + +- affected-user reproduction: use the same APEX end user or a comparable test user; +- Developer Toolbar or App Builder inspection: use an authorized APEX developer or workspace administrator; +- Monitor Activity, Debug, or Trace controls in the UI: use a browser user with the required workspace or instance administration rights; +- MCP/SQL correlation after browser triage: use the normal APEX Admin Identity Gate from `apex/admin/SKILL.md`; the browser login does not authorize MCP database access. + +For browser-guided tools such as Codex, the user can start with: + +```text +Use the APEX admin live browser debugging workflow. I am already signed in to APEX in this browser. This is a environment. Reproduce the issue on application , page . You may inspect visible UI, screenshots, browser console, and network metadata. Do not submit state-changing actions without asking me first. Do not use database access for this step. +``` + +If Debug or Trace is needed, ask for explicit confirmation and route the policy decision to `../monitoring/workspace-monitor-activity.md`. + +## Protocol File + +Before browser-guided debugging starts, load `protocol-file.md` and create or update the local operation protocol file. Use a browser-specific timestamped name such as `apex-browser-debug-protocol-YYYYMMDD-HHMMSS.md` when the user provides a directory. + +## Start Flow + +1. Confirm whether the browser session is a development, test, or production environment. +2. Confirm the target workspace or application, page, user journey, symptom, and approximate time window. +3. Ask for the local protocol output directory or exact file path if none was provided. +4. State that browser inspection alone does not require database access. +5. Create or update the protocol file with the initial scope before reproducing the issue. +6. Reproduce the issue with the smallest safe click path. +7. Capture only non-secret correlation facts: application ID or alias, page ID or title, visible error text, request timestamp with timezone, action name, AJAX or submit path, HTTP status, duration, and whether the behavior is reproducible. +8. If the browser evidence points to APEX runtime logs, load the relevant APEX monitoring reference. If it points to DB/ORDS evidence, stop and ask before handoff. + +## APEX Debug And Developer Toolbar + +Use the APEX Developer Toolbar or App Builder only when the user is already authenticated and authorized in that browser session. + +Allowed observations: + +- page ID, application ID, session information, visible session-state context, and debug links; +- page processing order, Dynamic Actions, validations, computations, processes, and visible component names; +- App Builder error pages or component settings relevant to the current symptom. + +Guardrails: + +- Do not enable Debug or Trace broadly from this reference. Use `../monitoring/workspace-monitor-activity.md` for Debug/Trace controls and require the narrow app/page/user/session/timebox there. +- Do not paste item values, cookies, authorization headers, credential static IDs, tokens, or full URLs with secrets into chat or artifacts. +- Do not use the Developer Toolbar to edit application definitions from this reference. Route app artifact changes to APEXlang or the appropriate APEX admin deployment workflow. + +## Network And Console Review + +Classify browser evidence by request type: + +- page render: initial document request, redirects, authentication, static asset loading; +- submit: `/wwv_flow.accept`, form submit, validations, page processing; +- AJAX: `/wwv_flow.ajax`, Dynamic Actions, plug-ins, lazy loading, Interactive Report/Grid calls; +- REST or external calls: REST Data Sources, Web Source calls, ORDS endpoints, third-party services; +- client-side issue: JavaScript exception, blocked asset, CORS, mixed content, missing static file, browser cache. + +For network review, record only metadata needed for triage: path shape, method, status, timing, initiator or action, response size class, and timestamp. HAR files must be redacted before use: remove cookies, authorization headers, bearer tokens, session IDs, request bodies, and secret-bearing URLs. + +For token efficiency, do not paste full network tables, DOM snapshots, screenshots, HAR files, or console dumps into chat. Update the protocol file with the few correlation facts that matter, then load deeper APEX monitoring references only when those facts point to a specific APEX-side next step. + +## Correlation Targets + +Use browser evidence to identify what to load next: + +- visible page latency, AJAX latency, request count, or slow render: `../monitoring/page-performance.md` and `../monitoring/activity-log.md`; +- error message, failed process, unhandled exception, or debug link: `../monitoring/error-handling.md`; +- reproduced multi-step journey or missing navigation step: `../monitoring/user-journey-replay.md`; +- REST, Web Source, or outbound call issue: `../monitoring/rest-data-sources.md`; +- automation, background process, or job symptom: `../monitoring/background-jobs.md`; +- SQL ID, wait event, AWR/ASH, SQL Monitor, ORDS pool, gateway, or infrastructure symptom: DB/ORDS skill handoff. + +When correlation uses live APEX SQL or APIs, apply the APEX Admin Identity Gate from `apex/admin/SKILL.md`. A browser session proves only browser authentication; it does not prove MCP database identity or permission to query APEX metadata. + +## State-Changing Browser Actions + +Ask for explicit confirmation before browser actions that can change state or create external side effects, including: + +- submitting forms that create, update, delete, approve, pay, send email, notify, start workflows, or call external systems; +- enabling Debug or Trace; +- changing App Builder settings or application definitions; +- rerunning jobs, automations, REST calls, imports, or deployment actions. + +Prefer a non-production environment for destructive or externally visible reproduction. If only production is available, keep the path read-only unless the user explicitly confirms the exact action. + +## Output Handling + +Keep browser-debug output compact: + +- local protocol file path and whether it was updated successfully; +- symptom reproduced or not reproduced; +- environment classification and browser-tool capability used; +- page/app/session/time correlation facts; +- console/network highlights without secrets; +- next APEX reference or DB/ORDS/APEXlang handoff. + +Do not store screenshots, HAR files, console dumps, customer paths, request payloads, or exported logs in the skill tree. If the user wants a report, follow the external-output rules in `apex/admin/SKILL.md`. diff --git a/apex/admin/references/debugging/protocol-file.md b/apex/admin/references/debugging/protocol-file.md new file mode 100644 index 0000000..5d98144 --- /dev/null +++ b/apex/admin/references/debugging/protocol-file.md @@ -0,0 +1,84 @@ +# Operation Protocol File + +Use this reference before any substantive live APEX admin workflow, state-changing workflow, customer-evidence analysis, or debugging workflow. + +Debugging includes: + +- live browser debugging through Codex or another browser-capable tool; +- APEX Debug or Trace; +- Activity Log, Page Performance, Error Log, Debug Messages, or Session Replay review; +- HAR, browser network, browser console, screenshot, or visible UI reproduction; +- any mixed browser plus MCP correlation workflow. + +## Location + +Create or update a local protocol file outside the skill tree before the workflow starts. + +The protocol is a local Markdown artifact, not a database logging table. Do not create or alter database tables, APEX internal/runtime tables, application tables, triggers, packages, or other schema objects for protocol storage. + +Do not write protocol files into: + +- `apex/admin`; +- `references`; +- `tools`; +- tests; +- committed documentation; +- any repository path unless the user explicitly asks for a sanitized, generic skill artifact. + +Ask for a user-confirmed output directory or exact Markdown file path. If the user gives a directory, create a timestamped Markdown filename: + +- `apex-admin-protocol-YYYYMMDD-HHMMSS.md` for general APEX admin work; +- `apex-debug-protocol-YYYYMMDD-HHMMSS.md` for APEX Debug, Trace, logs, or Session Replay; +- `apex-browser-debug-protocol-YYYYMMDD-HHMMSS.md` for browser-guided debugging. + +If no output path is provided, stop and ask for one before continuing. + +## Required Content + +Record concise, redacted facts: + +- local date/time and timezone; +- environment classification: development, test, production, managed service, or unknown; +- requested goal and APEX-admin scope; +- target workspace, application, page, user, session, request, and time window when known; +- active database identity or browser-session identity category; +- confirmation gates, including `SYSTEM` exact uppercase `YES` approval, destructive-action confirmations, Debug/Trace confirmations, and production reproduction confirmations; +- actions taken and whether they were read-only or state-changing; +- observations, error messages, timings, and correlation IDs; +- evidence references such as local file paths, report names, or redacted extract names; +- handoffs to APEXlang, DB, ORDS, or SQLcl skills; +- final status, limitations, and next step. + +## Token Efficiency + +Use the protocol file as a compact running summary for long investigations: + +- append short deltas instead of restating the full case; +- reference evidence by local path, report section, timestamp, request ID, page ID, or SQL label instead of copying full artifacts; +- keep raw APEX exports, AWR/ASH reports, HAR files, debug dumps, screenshots, console dumps, and logs outside chat context unless a small excerpt is required; +- summarize tool and SQL outputs before using them in follow-up reasoning; +- record open questions, confirmed facts, discarded hypotheses, and current next step so the agent does not reload the same references or reprocess the same evidence. + +If a later step needs details from a large artifact, search or parse the local file again and bring back only the relevant excerpt. + +## Redaction + +Never include: + +- passwords, cookies, session IDs, bearer tokens, OAuth secrets, API keys, wallet passwords, or authorization headers; +- request bodies, uploaded file contents, item values, secret-bearing full URLs, or unredacted HAR payloads; +- unnecessary personal data, customer secrets, production hostnames, or internal URLs unless explicitly needed and redacted. + +Summarize sensitive evidence instead of pasting it. Reference user-confirmed local paths for screenshots, HAR files, console dumps, or exported logs only when needed. + +## Updates + +Append short updates as work proceeds: + +- before enabling Debug or Trace; +- before state-changing browser or MCP actions; +- after each reproduction attempt; +- before and after DB/ORDS/APEXlang handoff; +- when stopping due to missing permissions, unsupported version, unsafe identity, unavailable MCP tools, or missing evidence. + +End with a compact summary of what was observed, what was changed if anything, what was not inspected, and where responsibility was handed off. diff --git a/apex/admin/references/deployment/deployment-identity.md b/apex/admin/references/deployment/deployment-identity.md new file mode 100644 index 0000000..b02742a --- /dev/null +++ b/apex/admin/references/deployment/deployment-identity.md @@ -0,0 +1,45 @@ +# Deployment Identity + +Use this topic when deciding which database identity should run an APEX-related deployment. Keep the decision explicit before generating install, import, or promotion steps. + +## Identity Types + +- **APEX instance admin identity**: Prefer a dedicated non-SYS/SYSTEM database account granted `APEX_ADMINISTRATOR_ROLE`. Use for APEX workspace lifecycle, workspace-schema mappings, APEX instance settings, and supported `APEX_INSTANCE_ADMIN` APIs. +- **Deployment or install identity**: A controlled compile-time account used to install or update database objects, grants, supporting objects, Liquibase changesets, or SQLcl Projects artifacts. Prefer least privilege and clear auditability. This may be an app-scoped admin user when the environment supports it. +- **App object owner identity**: The schema that owns application objects. Use when the environment requires app-user deployment or when installation is intentionally scoped to a single schema. +- **Runtime identity**: The schema or database account used by the running application. Keep runtime privileges smaller than compile-time deployment privileges. +- **DBA identity**: A privileged identity such as `SYS`, `SYSTEM`, `ADMIN`, or `SYSDBA`. Use only for explicit database administration, APEX installation/upgrade/patching when Oracle documentation requires it, emergency repair, or grant bootstrapping. +- **Privileged SYSTEM APEX admin identity**: `SYSTEM` without `SYSDBA` may be used for APEX-admin-scoped work only after the exact uppercase `YES` confirmation required by `apex/admin/SKILL.md`. + +## Decision Guide + +All live MCP-backed work that remains in the APEX admin skill must use a confirmed APEX instance admin identity. Do not use `SYS`, `SYSDBA`, app parsing schemas, workspace developers/end users, ORDS/APEX runtime accounts, or generic deployment users as the routine MCP/default connection. `SYSTEM` is allowed only as a privileged APEX admin identity after exact uppercase `YES` confirmation. + +On Autonomous Database or APEX Service, the service `ADMIN` account may be the available administration identity for APEX workspace provisioning or related APEX administration. Treat it as privileged: confirm `SESSION_USER`, `CURRENT_USER`, and `ISDBA`, ask the user whether to continue with that identity, and keep the work strictly APEX-admin-scoped. + +When the user intentionally chooses `SYSTEM`, it may run APEX-admin-scoped work only when `SESSION_USER = SYSTEM`, `CURRENT_USER = SYSTEM`, and `ISDBA = FALSE`. Show the exact target objects, exact SQL or SQLcl action class, password-handling path when relevant, and risk summary, then require the user to reply with exactly `YES` in uppercase. Do not put passwords in chat, scripts, SQL text, or logged MCP tool calls. This permits APEX admin account creation/grants, workspace lifecycle work, imports, monitoring queries, debug-log queries, and supported APEX API automation. It does not permit generic DB/ORDS/performance work. + +If a dedicated APEX instance admin identity is missing or `APEX_ADMINISTRATOR_ROLE` cannot be verified, do not fall through to a generic DBA path silently. Ask whether the user wants to use `SYSTEM` without `SYSDBA` once to create or repair the dedicated APEX admin account setup, or continue the APEX-admin-scoped workflow as `SYSTEM`. Either choice needs the exact uppercase `YES` confirmation from the APEX Admin Identity Gate. Do not create a look-alike `APEX_ADMINISTRATOR_ROLE` or grant broad DBA privileges as a shortcut. + +For password-based account creation or reset, use only a non-logged password path: an interactive local SQLcl prompt, a placeholder-backed local secret, or a user-run local password-generator command. Do not ask the user to paste passwords into chat, and do not generate or print passwords through MCP/tool output. + +For APEX application import metadata and `APEX_APPLICATION_INSTALL` calls handled by this skill, use the confirmed APEX admin identity. Confirm the target application, workspace, parsing schema, and whether the import updates an existing app or creates a new one. + +For new APEX application generation, route artifact creation to `apex/apexlang/SKILL.md` after announcing the skill handoff. Use this deployment identity topic only to decide whether the connected database user is appropriate for validation, materialization, import, or post-deploy checks. + +Before MCP-backed app creation, materialization, or import, verify `SESSION_USER`, `CURRENT_USER`, and `ISDBA`, show those values to the user, and continue only after the user confirms that the connection is the intended APEX admin identity. Do not continue silently from a previously active connection. + +For supporting database objects, SQLcl Projects, Liquibase, grants, cross-schema objects, app schema creation, database users/schemas, quotas, tablespaces, or ORDS configuration, route the database-deployment portion to the SQLcl/DB deployment skill. Ask the user for a separate DB administration connection or scoped provisioning identity required by that DB skill, such as a scoped install user, privilege-management account, `SYSTEM`, `ADMIN`, or another approved DB administration identity. The APEX admin skill may track the APEX import/promotion checklist, but it must not own generic schema deployment mechanics or silently reuse an APEX admin connection for DB-skill work. + +For shared databases, prefer app-user deployment or an app-scoped deployment identity so one application's installer cannot affect unrelated schemas. On Oracle Database versions that support schema-scoped administrative privileges, an app-scoped admin/install user may provide a better balance between automation and isolation. + +For read-only APEX performance triage, use either static evidence with no live database connection or a confirmed APEX admin identity. If the active connection is privileged but not the confirmed APEX admin identity, stop and ask for the correct APEX admin connection. If the evidence needed is AWR, ASH, `V$SESSION`, `V$SQL`, wait events, ORDS pool configuration, or system-level diagnostics, route that portion to the DB/ORDS/performance skill and use the DB skill's required connection/user. + +## Guardrails + +- Do not collapse compile-time deployment identity and runtime identity without explaining the security trade-off. +- Do not require app object owners to retain broad DDL privileges at runtime just because deployment is convenient. +- Do not recommend `DBA`, `SYSDBA`, `CREATE ANY TABLE`, `GRANT ANY PRIVILEGE`, or cross-schema `ANY` privileges for routine APEX work unless the user explicitly asks for privileged database deployment and the risk is called out. +- Do not use `SYS` for SQLcl/Liquibase deployment workflows. +- If `SYSTEM` or another privileged DB admin identity is proposed for deployment, classify the task as DB deployment unless the work is explicitly APEX-admin-scoped and the `SYSTEM` confirmation gate has passed. Require explicit scope and prefer a custom least-privilege install user where practical. Treat managed-service `ADMIN` as an APEX admin identity only when the user explicitly confirms that role for the APEX-scoped task. +- Record the selected identity model in deployment notes: `apex_instance_admin`, `deployment_install_user`, `app_object_owner`, `runtime_user`, or `dba_admin`. diff --git a/apex/admin/references/deployment/export-review.md b/apex/admin/references/deployment/export-review.md new file mode 100644 index 0000000..fb2ba0f --- /dev/null +++ b/apex/admin/references/deployment/export-review.md @@ -0,0 +1,36 @@ +# APEX Export Review + +APEX exports can contain sensitive metadata: URLs, authorization schemes, build options, substitution strings, static files, credential references, REST endpoints, defaults, install scripts, and business logic. Review before commit, sharing, or import. + +Use App Builder export or SQLcl APEX export workflows, but keep generic SQLcl syntax and CI/CD mechanics in the SQLcl DB skills. + +If the user's entry point is a customer-specific APEX application export file, including `.sql` or `.apx`, load `references/monitoring/apex-performance-evidence.md` first. Ask once whether additional evidence exists for the same case, such as APEX Activity Log/Page Performance, APEX Debug, HAR/Network, AWR/ASH, SQL Monitor, ORDS logs, deployment logs, or another export. If the user declines or no more files are available, continue with the export review or runtime-risk review using the available evidence and state the limits. + +Before starting a file-only export review, tell the user that the review is static and does not require database access. For customer exports, ask whether the result should stay chat-only or be saved to a user-confirmed external output path. Do not write customer-specific export findings under `apex/admin/` or anywhere else in the skill tree. If the review later needs live validation, stop before connecting and apply the APEX Admin Identity Gate or DB-skill handoff as appropriate. + +## Review Checklist + +- Application ID and alias are intentional for the target environment. +- Workspace and parsing schema mapping are explicit. +- Build options match the target environment. +- Substitution strings do not include real secrets or production-only endpoints unless intentionally deployed. +- Static files and supporting objects do not embed tokens, passwords, private URLs, or customer data. +- Authentication and authorization schemes are correct for the target environment. +- External links are intentional and use safe browser attributes where the export exposes link markup or attributes. For links opening a new browsing context, check for `rel="noopener noreferrer"` or an equivalent safe pattern unless the target platform contract requires different behavior. +- Web Credentials are referenced safely; secret values are not printed, committed, or copied into examples. +- REST Data Sources and remote server URLs are environment-aware. +- No real passwords, tokens, OAuth secrets, SMTP credentials, wallet passwords, web credential values, or secret-bearing URLs appear in exports, scripts, examples, logs, or chat output. + +## Output Summary + +For security-sensitive export reviews, include a compact checked/not-checked summary: + +- Checked: the APEX export surfaces actually inspected, such as substitution strings, static files, authentication, authorization, credentials, REST Data Sources, external links, and supporting objects. +- Not checked: unavailable evidence or intentionally skipped live validation, such as runtime logs, browser behavior, DB/ORDS diagnostics, or target-environment connectivity. +- Handoff: any generic DB, ORDS, SQLcl, or APEXlang responsibility routed out of this skill. + +## DB Skill Usage + +DB skill in use: `db/security/encryption.md`, `db/security/network-security.md`, or `db/security/privilege-management.md` for generic secret storage, TLS/network, and privilege implementation. The APEX deployment skill is being used for APEX export and credential-reference review. + +After this handoff, use the selected DB security skill's required connection/user. Do not reuse the APEX admin connection for grants, network ACLs, encryption, masking, or database secret-store changes unless the DB skill explicitly accepts it. diff --git a/apex/admin/references/deployment/import-promotion.md b/apex/admin/references/deployment/import-promotion.md new file mode 100644 index 0000000..a2a242e --- /dev/null +++ b/apex/admin/references/deployment/import-promotion.md @@ -0,0 +1,61 @@ +# APEX Import And Promotion + +Use `APEX_APPLICATION_INSTALL` when the import needs deterministic workspace, application ID, offset, alias, proxy, image prefix, or schema settings. Keep these calls in the import wrapper, not scattered through application code. + +Version check: inspect `ALL_ARGUMENTS` for `APEX_APPLICATION_INSTALL` in the target APEX release before using version-specific procedures or parameters. + +If the workflow creates or scaffolds a new APEX application artifact before import, announce the skill handoff and route that generation to APEXlang: + +```text +APEXlang skill in use: apex/apexlang/SKILL.md for APEX application generation. The APEX admin skill is being used only for workspace, deployment identity, connection safety, and post-deploy validation. +``` + +Before MCP-backed import or create-new materialization, verify the connection identity and continue only after the user confirms it is the intended APEX admin identity for the target workspace/import. Block `SYS`, `ISDBA = TRUE`, generic deployment users, parsing schemas, workspace users, ORDS/APEX runtime accounts, and unknown identities. If the identity is `SYSTEM`, continue only after the exact uppercase `YES` confirmation required by `apex/admin/SKILL.md`. Route generic database deployment work to the DB skill and use that skill's required connection/user. + +```sql +BEGIN + APEX_APPLICATION_INSTALL.SET_WORKSPACE(:target_workspace); + APEX_APPLICATION_INSTALL.SET_APPLICATION_ID(:target_application_id); + APEX_APPLICATION_INSTALL.SET_SCHEMA(:target_parsing_schema); + APEX_APPLICATION_INSTALL.SET_APPLICATION_ALIAS(:target_application_alias); +END; +/ +``` + +Check package arguments in the target APEX version before using less common procedures or parameters. Do not assume every APEX release supports the same install API shape. + +## Replace Safety + +For replace imports, list the existing target application and workspace before import and require explicit confirmation for production: + +```sql +SELECT workspace, + application_id, + application_name, + alias, + owner, + last_updated_on +FROM apex_applications +WHERE application_id = :target_application_id + OR UPPER(alias) = UPPER(:target_application_alias) +ORDER BY workspace, + application_id; +``` + +Treat these as destructive or high-risk: + +- Replace an existing application in production. +- Run supporting objects that drop or truncate tables. +- Delete or rotate APEX Web Credentials. +- Change authentication or authorization schemes. +- Change parsing schema mapping. +- Remove static files used by deployed pages. +- Import into a different workspace than expected. + +Safety stop: list affected workspace, application, parsing schema, authentication scheme, authorization schemes, credentials, and supporting objects. Require explicit confirmation before generating or running replace, delete, or destructive supporting-object steps. + +## DB Skill Usage + +DB skill in use: `db/devops/schema-migrations.md` and `db/devops/version-control-sql.md` for generic schema migration and release governance. The APEX deployment skill is being used for APEX application artifact promotion and environment mapping. + +After this handoff, use the selected DB skill's required connection/user for schema migration, SQLcl project, supporting-object, and database release-governance work. Do not reuse the APEX admin connection unless the DB skill explicitly accepts it. diff --git a/apex/admin/references/deployment/instance-admin-bootstrap.md b/apex/admin/references/deployment/instance-admin-bootstrap.md new file mode 100644 index 0000000..9a9faa6 --- /dev/null +++ b/apex/admin/references/deployment/instance-admin-bootstrap.md @@ -0,0 +1,134 @@ +# APEX Instance Administrator Bootstrap + +Use this topic when the user asks to create, reset, or unlock an APEX Instance Administrator for APEX Administration Services, especially for the `INTERNAL` workspace after a new self-managed or container-based APEX installation. + +This is installation/bootstrap work, not ordinary workspace-user administration. Do not route it to `APEX_UTIL.CREATE_USER`, and do not ask for a non-SYS/SYSTEM account with `APEX_ADMINISTRATOR_ROLE` as the primary path. + +Official source: Oracle APEX Installation Guide, "Creating or Updating Your Instance Administration Account" and "Running apxchpwd.sql": + +```text +https://docs.oracle.com/en/database/oracle/apex/26.1/htmig/downloading-installing-apex.html#GUID-4062E1F0-2772-48FC-A4AA-436F326CF751 +``` + +## Trigger Phrases + +Route here for prompts such as: + +- `can you create an apex instance admin` +- `create an APEX instance administrator` +- `an APEX internal/admin user for the INTERNAL workspace` +- `create an admin for INTERNAL` +- `reset the APEX Administration Services admin` +- `unlock the APEX instance administrator` + +Do not respond by asking whether this means a database account granted `APEX_ADMINISTRATOR_ROLE`. Ask that only when the user says "database account", "grant role", or otherwise describes a database-login administrator rather than the APEX Administration Services administrator. + +## When To Use apxchpwd.sql + +Before giving local script steps, ask whether the environment is self-managed/container-based, co-managed Cloud with host/database access, or fully managed. Do not infer this from the service name alone. + +For self-managed/container/co-managed Cloud APEX installations where the user can access the APEX installation directory and connect to the target database as `SYS AS SYSDBA`, run `apxchpwd.sql` from the APEX installation directory to create or update the Instance Administrator account. Use it for: + +- New Oracle APEX installations where no Instance Administrator exists yet. +- Runtime-to-development conversion where the Instance Administrator password must be set. +- Changing an existing Instance Administrator password. +- Unlocking an existing Instance Administrator account. + +`apxchpwd.sql` is not supported on Oracle Autonomous AI Database or Oracle APEX AI Application Generator Service (APEX Service). For those managed services, do not give local script steps. Tell the user this is managed-service administration and route them to the service-specific console/documentation path for creating, resetting, or unlocking the APEX Administration Services account. + +Example managed-service response: + +```text +This environment is managed, so I should not give apxchpwd.sql commands. Use the service-specific administration/reset path for APEX Administration Services instead. I can help identify the right console/documentation path, but I will not ask for or handle the APEX admin password in chat. +``` + +## Required Connection + +Run the script in the database/PDB where APEX is installed. Start SQLcl from the directory where the APEX installation ZIP was unpacked and connect as `SYS AS SYSDBA`. + +This privileged connection is allowed here because the task is explicit APEX installation/bootstrap work. Do not use this exception for routine workspace creation, workspace-user changes, application import, monitoring, or APEX API automation. + +## Password-Safe Handling + +Do not ask the user to send the Instance Administrator password in chat. + +Do not run `apxchpwd.sql` through `sql_run`. SQLcl MCP commands and SQL statements are logged, and the script is interactive. Give the user a terminal sequence with placeholders and instruct them to enter the password only at the script prompt. + +## Confirmation Gate + +Before giving final commands or telling the user to proceed, summarize all non-secret details and require explicit confirmation. + +Confirm at least: + +- Action: create, reset, unlock, or bootstrap an APEX Instance Administrator. +- Environment type: self-managed/container/co-managed Cloud or managed Autonomous AI Database/APEX Service. +- Target database, PDB, or service name. +- APEX installation directory containing `apxchpwd.sql`, only for self-managed/container/co-managed Cloud. +- Instance Administrator username. +- Email address. + +Use a confirmation prompt like: + +```text +Please confirm these details before I give the final apxchpwd.sql run commands: + +Action: +Environment: +Target database/PDB/service: +APEX install directory: +Instance Administrator username: +Email: + +Do not send the password in chat. Reply with "confirmed" only if these non-secret details are correct. +``` + +Do not proceed from inferred values, remembered context, or partial confirmation. If anything changes, restate the full confirmed set before giving final commands. + +Example response when details are missing: + +```text +Yes. For an APEX Instance Administrator in the INTERNAL workspace after a self-managed/container installation, use apxchpwd.sql; this is not a normal APEX workspace user create. + +First I need to confirm whether this is self-managed/container/co-managed Cloud or a managed Autonomous AI Database/APEX Service environment. If it is self-managed/container/co-managed Cloud, I also need the APEX install directory, target database/PDB/service name, desired username, and email address so I can summarize the non-secret details for confirmation. Do not send the APEX admin password in chat. +``` + +Example response when enough environment detail is known: + +```text +Please confirm these details before I give the final apxchpwd.sql run commands: + +Action: create or update an APEX Instance Administrator +Environment: +Target database/PDB/service: +APEX install directory: +Instance Administrator username: +Email: + +Do not send the password in chat. Reply with "confirmed" only if these non-secret details are correct. +``` + +Example final response after explicit confirmation: + +```text +Run this from a shell on the database host or container, replacing the placeholders: + +cd +sql /nolog +CONNECT SYS@ AS SYSDBA +@apxchpwd.sql + +Enter the Instance Administrator username, email address, and password only when apxchpwd.sql prompts for them. If the username does not exist, the script creates it; if it exists, it updates/unlocks it. +``` + +If the user is working inside an Oracle container and the image did not create the APEX Instance Administrator, tell them to exec into the container, change to the unpacked APEX installation directory, connect to the database/PDB where APEX was installed as `SYS AS SYSDBA`, and run `@apxchpwd.sql`. + +## Checks Before Giving Steps + +Ask for or confirm: + +- Whether the environment is self-managed/container-based, co-managed Cloud with host/database access, or managed Autonomous AI Database/APEX Service. +- The target database, PDB, or service name where APEX is installed. +- The APEX installation directory that contains `apxchpwd.sql`, only for self-managed/container/co-managed Cloud. +- The desired Instance Administrator username and email address, if they want a concrete runbook. + +Do not require a saved SQLcl MCP connection for the password-setting step. If MCP is used at all, keep it to read-only checks such as APEX version or PDB identification, and still do not collect or log the Instance Administrator password. diff --git a/apex/admin/references/deployment/patching.md b/apex/admin/references/deployment/patching.md new file mode 100644 index 0000000..9006ee6 --- /dev/null +++ b/apex/admin/references/deployment/patching.md @@ -0,0 +1,144 @@ +# APEX Patch Set Bundle Workflow + +Use this topic for Oracle APEX Patch Set Bundle status checks and patch planning. Patch availability is time-sensitive, so verify the latest patch number, patch version, README, and known issues from Oracle before giving exact patch instructions. + +Use this for self-managed or co-managed environments. For fully managed Autonomous Database or APEX Application Development Service, Oracle normally applies APEX patch bundles; do not advise manual patching unless the service documentation says patching is customer-managed. + +Live MCP-backed APEX patch-status checks in this skill require the confirmed APEX admin identity from `apex/admin/SKILL.md`. Privileged patch execution, database backup/restore, invalid-object repair, and ORDS runtime administration are DB/ORDS-skill work and must use those skills' required connection/user. + +## Version And View Availability + +Check APEX version first: + +```sql +SELECT version_no +FROM apex_release; +``` + +Check whether `APEX_PATCHES` is available and which columns exist before querying patch rows: + +```sql +SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name = 'APEX_PATCHES' +ORDER BY column_id; +``` + +Then query installed patch rows: + +```sql +SELECT patch_number, + patch_version, + installed_on +FROM apex_patches +ORDER BY installed_on; +``` + +If `APEX_PATCHES` returns no rows, that only means no patch rows are recorded in that view for the current APEX installation. It does not prove that the system is unsupported or broken. Compare `APEX_RELEASE.VERSION_NO` with the latest official APEX release and patch bundle information. + +## Find The Latest Patch Bundle + +Before recommending a patch number: + +- Check the Oracle APEX Downloads and Known Issues page. +- Check My Oracle Support for the target APEX release. +- Read the patch README included in the downloaded patch bundle. +- Confirm whether the patch applies to the exact installed APEX base release. + +As of May 11, 2026, Oracle's APEX downloads page lists Patch Set Bundle for Oracle APEX 24.2 as patch `37366599`, last updated April 30, 2026, with `PATCH_VERSION` 16. Oracle states that applying it updates the APEX product version to `24.2.16`. Treat this as a dated reference point, not a permanent rule. + +## High-Level Patch Flow + +Follow the patch README for exact commands. Use this as the operational checklist: + +1. Confirm target PDB and installed APEX version. +2. Query `APEX_PATCHES`. +3. Download the matching APEX Patch Set Bundle from My Oracle Support. +4. Read the patch README completely. +5. Back up the database/PDB and export critical APEX applications. +6. Stop ORDS or put APEX behind maintenance if the README or local policy requires it. +7. Unzip the patch on the database host or approved deployment host. +8. After the DB/admin skill handoff, connect to the PDB where APEX is installed with the required administrative privileges, typically `SYS AS SYSDBA` when the README requires it. +9. Run the patch script from the extracted patch directory exactly as documented. +10. Recompile invalid objects. +11. Update APEX static files, or set the image prefix to the matching Oracle CDN path when CDN images are used. +12. Restart or reload ORDS. +13. Verify APEX version, patch rows, invalid objects, App Builder, application runtime, and static resources. + +## Post-Patch Verification + +```sql +SELECT version_no +FROM apex_release; +``` + +```sql +SELECT patch_number, + patch_version, + installed_on +FROM apex_patches +ORDER BY installed_on; +``` + +```sql +SELECT owner, + object_type, + COUNT(*) AS invalid_objects +FROM dba_objects +WHERE status = 'INVALID' + AND owner LIKE 'APEX\_%' ESCAPE '' +GROUP BY owner, object_type +ORDER BY owner, object_type; +``` + +Also verify: + +- APEX Administration Services opens. +- At least one workspace can sign in. +- App Builder opens without JavaScript/CSS errors. +- A representative runtime application works. +- Browser developer tools show no missing `/i/` static resources. +- ORDS logs have no new APEX static-resource or pool errors. + +## Static Files And CDN + +APEX patches can require static file updates. The database APEX version and the served image files must match. + +If using local images: + +- Copy the patched `images` directory according to the README. +- Confirm ORDS or the web server serves the updated `/i/` path. + +If using Oracle CDN: + +- Confirm the known-issues/downloads page lists a CDN URL for the exact patched APEX version. +- Set the image prefix only to the matching version path. +- Test App Builder and runtime pages for missing assets. + +## Autonomous And Managed Services + +For Autonomous Database and APEX Application Development Service: + +- Check `APEX_RELEASE` and `APEX_PATCHES`. +- Report the observed version and patch rows. +- Do not instruct the user to manually download and apply a patch bundle unless Oracle service documentation explicitly says that patching is customer-managed. +- If the environment is behind the latest published patch, advise checking the service maintenance schedule or opening an Oracle Support service request. + +## DB Skill Usage + +DB skill in use: `db/admin/backup-recovery.md` for generic database backup and restore planning. The APEX deployment skill is being used for APEX patch-bundle workflow context. + +DB skill in use: `db/ords/ords-monitoring.md` for generic ORDS runtime checks. The APEX deployment skill is being used for APEX static-file and App Builder verification context. + +After a DB/ORDS-skill handoff, use the selected skill's required connection/user. Do not reuse the APEX admin connection for backup, restore, patch execution, invalid-object repair, or ORDS diagnostics unless the selected skill explicitly accepts it. + +## Guardrails + +- Do not treat `APEX_PATCHES` with no rows as proof that the newest patch is missing. +- Do not apply a patch bundle to the wrong APEX base version. +- Do not run patch scripts in `CDB$ROOT` unless the patch README explicitly instructs it. +- Do not forget to update static files or CDN image prefix. +- Do not give a hard-coded latest patch number without checking Oracle first. diff --git a/apex/admin/references/deployment/post-deploy-validation.md b/apex/admin/references/deployment/post-deploy-validation.md new file mode 100644 index 0000000..046324e --- /dev/null +++ b/apex/admin/references/deployment/post-deploy-validation.md @@ -0,0 +1,24 @@ +# APEX Post-Deploy Validation + +Validate APEX-specific behavior after import. + +Live MCP-backed APEX validation queries must use the confirmed APEX admin identity from `apex/admin/SKILL.md`. If validation crosses into generic database auditing, grants, runtime schemas, ORDS, or infrastructure checks, route that portion to the DB skill and use that skill's required connection/user. + +## Validation Checklist + +- Application exists in the expected workspace with the expected ID, alias, owner, and parsing schema. +- Build options and substitution strings match target environment policy. +- Authentication and authorization schemes work for Workspace Admin, Developer, End User, parsing schema, database-login user, ORDS/APEX runtime account, and DBA/admin account boundaries. +- REST Data Sources and Web Credentials resolve without exposing secret values. +- Critical pages compile and run with expected authorization and session-state protection. +- Supporting objects ran only when intended and did not perform surprise destructive work. +- APEX activity/debug/error logs are free of deployment-time secret leakage. + +## Security Review + +- Privileges remain least-privilege. +- No broad grants such as `DBA`, `SELECT ANY TABLE`, `EXECUTE ANY PROCEDURE`, `CREATE ANY TABLE`, `GRANT ANY ROLE`, or `GRANT ANY PRIVILEGE` were introduced for ordinary APEX deployment. +- APEX session state, hidden items, read-only items, and client-side checks are not treated as security boundaries. +- Any database auditing requirement is handled by the DB auditing skill. + +DB skill in use: `db/security/auditing.md` for generic database audit policy and evidence handling. The APEX deployment skill is being used for APEX release traceability and post-import validation context. diff --git a/apex/admin/references/deployment/pre-check.md b/apex/admin/references/deployment/pre-check.md new file mode 100644 index 0000000..f576c8a --- /dev/null +++ b/apex/admin/references/deployment/pre-check.md @@ -0,0 +1,139 @@ +# APEX Deployment Pre-Check + +Before generating import SQL or deployment steps, identify: + +- Installed APEX version and whether it passes the supported-version gate in `references/workspace/version-notes.md`. +- Source and target workspace names and workspace IDs. +- Source and target application IDs and whether the target ID must be preserved or remapped. +- Parsing schema mapping and whether schemas already exist. +- Target APEX version and managed-service restrictions. +- Authentication scheme, authorization schemes, build options, substitution strings, application settings, static files, supporting objects, web credentials, and REST Data Sources. +- Whether the import will replace an existing application, install supporting objects, overwrite shared components, or run post-install code. + +## Application Generation Handoff + +If the request is to create or scaffold a new APEX application rather than only prepare an import or deployment pre-check, announce the handoff before generating app artifacts: + +```text +APEXlang skill in use: apex/apexlang/SKILL.md for APEX application generation. The APEX admin skill is being used only for workspace, deployment identity, connection safety, and post-deploy validation. +``` + +Then load `apex/apexlang/SKILL.md` and follow the APEXlang application-generation workflow. Keep this deployment pre-check open only for target workspace, parsing schema, deployment identity, import/promotion, and post-deploy validation decisions. + +For MCP-backed app creation, materialization, validation, or import, verify the active database identity before proceeding: + +```sql +SELECT SYS_CONTEXT('USERENV', 'SESSION_USER') AS session_user, + SYS_CONTEXT('USERENV', 'CURRENT_USER') AS current_user, + SYS_CONTEXT('USERENV', 'ISDBA') AS is_dba +FROM dual; +``` + +```text +Connection confirmation: I am connected as SESSION_USER=, CURRENT_USER=, ISDBA=. This APEX admin workflow requires the intended APEX admin identity. Confirm this connection is the APEX admin identity for the target workspace/import before I continue. +``` + +If `SESSION_USER` or `CURRENT_USER` is `SYS`, `IS_DBA` is `TRUE`, or the user cannot confirm this is the APEX admin identity, stop and ask for the confirmed APEX admin connection. If the identity is `SYSTEM`, continue only after the exact uppercase `YES` confirmation required by `apex/admin/SKILL.md`. Do not use a generic deployment user inside this APEX admin skill; route generic database deployment work to the DB skill and use that skill's required connection/user. + +## Version And Package Checks + + +For APEX installation or upgrade pre-checks, identify: + +- Database version and whether the target is CDB/PDB. +- Exact PDB where APEX is or will be installed. +- Existing APEX version, if any. +- ORDS version and deployment mode. +- Whether APEX static files are served by ORDS local images, web server images, or Oracle CDN. +- Backup and rollback plan. +- Maintenance window and affected applications/workspaces. + +For fully managed Autonomous Database or APEX Application Development Service, do not plan a manual APEX installation unless Oracle documentation for that service explicitly allows it. For self-managed environments, follow the APEX installation guide for the exact target version. + +Before installation or upgrade, confirm: + +- A tested database/PDB backup or restore point exists. +- Static files and image prefix handling are planned before the maintenance window. +- ORDS can be stopped, reloaded, or placed behind maintenance according to local policy. + +Before relying on an APEX API signature or installation behavior, use official Oracle APEX documentation. Start with APEX 26.1: + +```text +https://docs.oracle.com/en/database/oracle/apex/26.1/htmrn/ +https://docs.oracle.com/en/database/oracle/apex/26.1/htmig/ +https://docs.oracle.com/en/database/oracle/apex/26.1/aeapi/ +``` + +Use APEX 24.2 or APEX 24.1 documentation only when the installed or target environment is that APEX release: + +```text +https://docs.oracle.com/en/database/oracle/apex/24.2/ +https://docs.oracle.com/en/database/oracle/apex/24.1/ +``` + +Do not use APEX documentation older than 24.1 unless the user explicitly asks for legacy-version migration or compatibility analysis. If the target version is unknown, use APEX 26.1 as the default reference and keep SQL version-tolerant. + +Use APEX Diff as a convenience helper to compare standard APEX Dictionary +views and public PL/SQL APIs across source and target releases, including +current releases such as APEX 26.1 when they are listed there, before choosing +deployment pre-check SQL or `APEX_APPLICATION_INSTALL` calls: + +```text +https://apexadb.oracle.com/ords/r/apexdiff/apex_diff/home +``` + +Verify any suggested view, column, package, procedure, or argument on the +target instance with `APEX_RELEASE`, `APEX_DICTIONARY`, `ALL_TAB_COLUMNS`, and +`ALL_ARGUMENTS` before generating final deployment SQL. + +Check APEX version and package signatures before version-specific calls: + +```sql +SELECT version_no +FROM apex_release; + +SELECT object_name, + argument_name, + position, + data_type +FROM all_arguments +WHERE package_name = 'APEX_APPLICATION_INSTALL' +ORDER BY object_name, + sequence; +``` + +Discover available APEX metadata views before querying deployment metadata: + +```sql +SELECT view_name, + comments +FROM apex_dictionary +WHERE view_name LIKE 'APEX_APPLICATION%' + OR view_name LIKE 'APEX_APPL%' +ORDER BY view_name; +``` + +```sql +SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name IN ( + 'APEX_APPLICATIONS', + 'APEX_APPLICATION_BUILD_OPTIONS', + 'APEX_APPLICATION_SUBSTITUTIONS', + 'APEX_WORKSPACE_CREDENTIALS', + 'APEX_APPLICATION_STATIC_FILES') + OR table_name LIKE 'APEX_APPLICATION%AUTH%' +ORDER BY table_name, + column_id; +``` + +## DB Skill Usage + +DB skill in use: `db/sqlcl/sqlcl-basics.md`, `db/sqlcl/sqlcl-scripting.md`, or `db/sqlcl/sqlcl-cicd.md` for generic SQLcl commands and CI/CD mechanics. The APEX deployment skill is being used for APEX metadata and import semantics. + +DB skill in use: `db/security/privilege-management.md` for generic deployment-account, parsing-schema, and runtime-account privilege analysis. The APEX deployment skill is being used for APEX export/import context and environment mapping. + +After a DB-skill handoff, use the selected DB skill's required connection/user for SQLcl workflows, schema deployment, grants, deployment-account setup, and runtime-account privilege analysis. Do not reuse the APEX admin connection unless the DB skill explicitly accepts it. diff --git a/apex/admin/references/deployment/security-review.md b/apex/admin/references/deployment/security-review.md new file mode 100644 index 0000000..367e976 --- /dev/null +++ b/apex/admin/references/deployment/security-review.md @@ -0,0 +1,15 @@ +# APEX Deployment Security Review + +Use this checklist after substantial APEX deployment or promotion work. + +- Scope: APEX export/import, `APEX_APPLICATION_INSTALL`, App Builder settings, workspace/application mapping, and APEX metadata stayed in this skill; generic SQLcl, schema migration, privilege, encryption, auditing, network, ORDS, or CI/CD work was routed to `db/...`. +- DB usage messages: every generic DB step has a visible `DB skill in use:` message naming the relevant DB skill path. +- APEX admin identity: every live MCP-backed APEX admin step ran under the confirmed APEX admin identity, not `SYS`, `SYSDBA`, a parsing schema, workspace user, ORDS/APEX runtime account, generic deployment user, or unknown account. If `SYSTEM` was used, the exact uppercase `YES` confirmation, scope, targets, and risk summary were recorded before work continued. +- Protocol file: deployment review, import/promotion, patch-status, post-deploy validation, and debugging workflows created or updated a local protocol file outside the skill tree before the work began. +- DB handoff identity: every generic DB step used the selected DB skill's required connection/user rather than silently reusing the APEX admin connection. +- Privileges: APEX admin, deployment accounts, parsing schemas, workspace administrators, developers, database-login users, ORDS/APEX runtime accounts, and DBA/admin accounts remain separate and least-privilege. +- Secrets: no real passwords, tokens, OAuth secrets, SMTP credentials, wallet passwords, web credential values, or secret-bearing URLs appear in exports, scripts, examples, logs, or chat output. +- Data exposure: static files, supporting objects, substitution strings, REST Data Sources, debug logs, and exports do not expose unnecessary payloads, BLOBs, CLOBs, credentials, or sensitive metadata. +- Version/cloud restrictions: APEX version, install package signatures, managed-service restrictions, and available metadata views were checked before version-specific SQL or import steps. +- Destructive actions: replace imports, supporting objects, credential changes, app deletion, schema mapping changes, and production imports list affected objects and require explicit confirmation. +- Auditability: export source, import target, application ID, workspace, parsing schema, build options, release artifact, and operator are traceable. diff --git a/apex/admin/references/monitoring/activity-log.md b/apex/admin/references/monitoring/activity-log.md new file mode 100644 index 0000000..2b6a109 --- /dev/null +++ b/apex/admin/references/monitoring/activity-log.md @@ -0,0 +1,106 @@ +# APEX Activity Log Triage + +Use this reference for `APEX_WORKSPACE_ACTIVITY_LOG`, `APEX_ACTIVITY_LOG`, usage/load trends, and session drilldown. + +For broad APEX application performance analysis, load `apex-performance-evidence.md` first to ask for available APEX, browser, AWR/ASH, SQL Monitor, and ORDS evidence and the output path for customer-specific results. + +## View Pre-Check + +APEX view columns vary by release and privilege. Inspect availability before version-specific SQL. + +Use APEX Diff as a convenience helper to compare activity-log, Team +Development, and related standard APEX views across releases before choosing +monitoring calls, including current releases such as APEX 26.1 when they are +listed there. Verify the installed target locally with `APEX_DICTIONARY`, +`ALL_OBJECTS`, and `ALL_TAB_COLUMNS`: + +```text +https://apexadb.oracle.com/ords/r/apexdiff/apex_diff/home +``` + +```sql +SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name IN ( + 'APEX_WORKSPACE_ACTIVITY_LOG', + 'APEX_ACTIVITY_LOG') +ORDER BY table_name, + column_id; +``` + +```sql +SELECT owner, + object_name, + object_type +FROM all_objects +WHERE object_name IN ( + 'APEX_WORKSPACE_ACTIVITY_LOG', + 'APEX_ACTIVITY_LOG') +ORDER BY object_name, + owner; +``` + +## Usage And Load Trends + +Group by workspace and application first, then drill into pages after identifying the noisy application. + +```sql +SELECT TRUNC(view_date, 'HH24') AS hour_start, + workspace, + application_id, + application_name, + COUNT(*) AS page_events, + COUNT(DISTINCT apex_session_id) AS apex_sessions, + ROUND(AVG(elapsed_time), 3) AS avg_elapsed_seconds, + ROUND(PERCENTILE_CONT(0.95) + WITHIN GROUP (ORDER BY elapsed_time), 3) AS p95_elapsed_seconds, + MAX(elapsed_time) AS max_elapsed_seconds +FROM apex_workspace_activity_log +WHERE view_date >= SYSDATE - 1 +GROUP BY TRUNC(view_date, 'HH24'), + workspace, + application_id, + application_name +ORDER BY hour_start, + page_events DESC; +``` + +## Session Drilldown + +Use this when a user reports one bad session. Avoid selecting request payloads or sensitive item values by default. + +```sql +SELECT view_date, + workspace, + apex_user, + apex_session_id, + application_id, + page_id, + page_name, + page_view_type, + request_value, + elapsed_time, + rows_queried, + error_message +FROM apex_workspace_activity_log +WHERE apex_session_id = :apex_session_id +ORDER BY view_date, + id; +``` + +Look for latency jumps, AJAX storms, repeated authentication callbacks, missing expected page steps, and component errors. + +## DB Skill Usage + +If the user provides AWR, ASH, wait-event output, SQL Monitor, execution plans, `V$`/`DBA_HIST` evidence, or ORDS runtime diagnostics after the APEX workspace, application, page, session, and time window are identified, ask before switching to the DB skill. Do not interpret generic DB evidence inside this APEX activity-log reference, and do not reuse the APEX admin connection for live DB-skill work unless the DB skill explicitly accepts it. + +Use this handoff only after confirmation: + +```text +DB skill in use: db/performance/wait-events.md, db/performance/ash-analysis.md, or db/performance/awr-reports.md for generic database performance interpretation. The APEX monitoring skill is being used for activity-log context. +``` + +After this handoff, use the selected DB performance skill's required connection/user, such as a diagnostics/performance account for AWR, ASH, `DBA_HIST`, `V$`, SQL Monitor, or execution-plan evidence. diff --git a/apex/admin/references/monitoring/ai-token-monitoring.md b/apex/admin/references/monitoring/ai-token-monitoring.md new file mode 100644 index 0000000..f050fc4 --- /dev/null +++ b/apex/admin/references/monitoring/ai-token-monitoring.md @@ -0,0 +1,195 @@ +# APEX AI Token Monitoring + +Use this reference when the user asks about APEX Generative AI token usage, token limits, remaining tokens, AI service utilization, AI service history, or token consumption per workspace, application, service, or provider. + +Official sources: + +```text +https://docs.oracle.com/en/database/oracle/apex/26.1/htmrn/new-features.html +https://docs.oracle.com/en/database/oracle/apex/26.1/htmdb/creating-generative-ai-service-objects.html +https://docs.oracle.com/en/database/oracle/apex/26.1/htmdb/viewing-generative-ai-service-utilization.html +https://docs.oracle.com/en/database/oracle/apex/26.1/htmdb/viewing-generative-ai-service-history.html +https://docs.oracle.com/en/database/oracle/apex/26.1/htmdb/configuring-ai-attributes-for-an-application.html +https://docs.oracle.com/en/database/oracle/apex/26.1/aeapi/APEX_AI.GET_AVAILABLE_TOKENS-Function.html +https://docs.oracle.com/en/database/oracle/apex/26.1/aeapi/APEX_AI.Data-Types.html +``` + +APEX 26.1 supports Generative AI token usage limits at instance, workspace, AI service, and vector provider level. Token enforcement depends on whether the AI provider returns token usage information. + +## Scope + +Keep this work in the APEX admin skill when the task is: + +- Inventory APEX AI services and which apps/components use them. +- Review workspace, service, provider, or app AI token limits. +- Check remaining tokens through supported APEX APIs. +- Correlate APEX app/service usage with APEX activity, debug, or web service logs. +- Identify whether per-application token consumption is directly available in the installed APEX version. + +Route out of this skill when the task is: + +- Provider billing, OCI tenancy billing, model pricing, or external quota management. +- Generic database performance, waits, SQL tuning, ORDS pool behavior, or network analysis. +- Application code changes for custom instrumentation beyond a recommendation. + +## Identity Gate + +Live MCP-backed checks require the confirmed APEX admin identity from `apex/admin/SKILL.md`. Do not query APEX AI metadata, activity logs, debug logs, or APEX APIs under `SYS`, `SYSDBA`, app parsing schemas, workspace users, ORDS/APEX runtime users, generic deployment users, or unknown accounts. `SYSTEM` is allowed only after the exact uppercase `YES` confirmation required by the APEX Admin Identity Gate. + +Static review of APEX exports does not require database access. Announce that boundary before file-only analysis. + +## First Questions + +Ask only what is needed: + +- Which workspace and application IDs or aliases should be reviewed? +- Is the goal remaining tokens, consumed tokens, utilization by app, or limit governance? +- Is the time window needed for usage/history analysis? +- Are AI services shared across apps, or should each app have its own service for clean accounting? + +## Discovery + +Before assuming view, column, or API availability, inspect the installed APEX version and dictionary. + +```sql +SELECT version_no +FROM apex_release; +``` + +```sql +SELECT view_name, + comments +FROM apex_dictionary +WHERE UPPER(view_name) LIKE '%AI%' + OR UPPER(view_name) LIKE '%GEN%' + OR UPPER(view_name) LIKE '%WEBSERVICE%LOG%' +ORDER BY view_name; +``` + +```sql +SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE UPPER(table_name) LIKE 'APEX%AI%' + OR UPPER(table_name) LIKE 'APEX%GEN%AI%' + OR table_name IN ( + 'APEX_APPLICATIONS', + 'APEX_WEBSERVICE_LOG') +ORDER BY table_name, + column_id; +``` + +Check public APEX AI API availability before generating API calls. + +```sql +SELECT owner, + package_name, + object_name, + argument_name, + position, + data_type, + in_out +FROM all_arguments +WHERE package_name = 'APEX_AI' + AND object_name IN ( + 'GET_AVAILABLE_TOKENS', + 'GENERATE', + 'CHAT') +ORDER BY owner, + package_name, + object_name, + sequence; +``` + +Do not call internal `WWV_FLOW_%` packages or query internal APEX repository tables as the default path. If the only token-consumption API found is internal or undocumented, state that it is unsupported for this skill and ask whether the user wants a separate, explicitly risk-accepted investigation. + +## Remaining Tokens + +Use the public `APEX_AI.GET_AVAILABLE_TOKENS` API when available. + +Prefer an explicit AI service static ID for MCP/SQLcl checks because there may be no current APEX application runtime context: + +```sql +SELECT apex_ai.get_available_tokens( + p_service_static_id => :service_static_id + ) AS available_tokens +FROM dual; +``` + +Without `p_service_static_id`, the function uses the default AI service of the current application context. Do not assume that context exists in a standalone SQLcl or MCP database session. + +## Consumed Tokens Per Application + +Per-application consumed-token reporting is version- and provider-dependent. + +Use this decision order: + +1. Prefer documented APEX UI reports such as Generative AI Service Utilization and Generative AI Service History when they provide the needed app, service, time-window, and token columns. +2. Use public `APEX_*` views only after `APEX_DICTIONARY` and `ALL_TAB_COLUMNS` prove that application identifiers and token columns exist in the installed version. +3. If a public procedure or function is discovered for token consumption, inspect its arguments first and use only documented or public APEX APIs. +4. If no public app-level token counter exists, report app-level consumption as unavailable from APEX admin metadata and recommend either service-level accounting or application-side instrumentation. + +For any discovered public view with `APPLICATION_ID` plus token columns such as `INPUT_TOKENS`, `OUTPUT_TOKENS`, or `TOTAL_TOKENS`, aggregate only after confirming the exact table and column names: + +```sql +-- Shape only. Replace view and column names only after dictionary discovery. +SELECT application_id, + service_static_id, + SUM(input_tokens) AS input_tokens, + SUM(output_tokens) AS output_tokens, + SUM(total_tokens) AS total_tokens, + MIN(request_timestamp) AS first_seen, + MAX(request_timestamp) AS last_seen +FROM +WHERE request_timestamp >= :from_timestamp + AND request_timestamp < :to_timestamp +GROUP BY application_id, + service_static_id +ORDER BY total_tokens DESC; +``` + +Do not present service-level totals as per-app totals when multiple applications share the same AI service and the usage evidence does not include `APPLICATION_ID`. + +## Application-Side Instrumentation + +If APEX admin metadata cannot prove per-app consumption, application-owned instrumentation is the reliable path. `APEX_AI` response data types expose token fields such as input, output, and total tokens when the provider returns them. + +The APEX admin skill may recommend application-side instrumentation, but it must not create or alter the instrumentation objects. Route implementation to the owning APEXlang or DB skill after explicit user confirmation. + +An application-owned implementation may record: + +- Application ID and page ID. +- AI service static ID. +- User/session/request context when appropriate. +- Input, output, and total token counts returned by `APEX_AI`. +- Provider/model and timestamp. + +Keep implementation details in the APEX application or DB skill as appropriate; this monitoring reference may recommend the pattern but must not own application-code changes, DDL, triggers, packages, or writes to customer-owned tables. + +## Interpretation + +- Remaining tokens answer "how much quota is left"; they do not prove historical app-level consumption. +- Service utilization answers "where this service is used"; it may not prove exact consumed tokens per app. +- Provider billing can differ from APEX token counters. Treat provider-side invoices and pricing as external evidence. +- Token limits and counters are only meaningful when the provider reports token usage. +- Shared AI services reduce accounting clarity. Use dedicated services or instrumentation when per-app chargeback is required. + +## Review Output + +Summaries should include: + +- Workspace and app scope. +- AI services and whether they are shared. +- Limit level reviewed: instance, workspace, service, vector provider, or application default service. +- Remaining tokens when available. +- Consumed tokens per app only when proven by public APEX metadata or instrumentation. +- Evidence gaps and whether provider token reporting is supported. + +## Security Review + +- Do not print prompts, completions, embeddings, item values, authorization headers, API keys, OAuth tokens, or credential values unless explicitly required and approved. +- Treat AI prompts and outputs as sensitive application data. +- Do not expose model endpoints, tenancy URLs, or credential static IDs beyond what the user needs. +- Keep provider billing and pricing evidence separate from APEX admin metadata. diff --git a/apex/admin/references/monitoring/apex-performance-evidence.md b/apex/admin/references/monitoring/apex-performance-evidence.md new file mode 100644 index 0000000..5c54353 --- /dev/null +++ b/apex/admin/references/monitoring/apex-performance-evidence.md @@ -0,0 +1,68 @@ +# APEX Performance Evidence Intake + +Use this reference at the start of an APEX application performance analysis, especially when the user provides only one evidence source such as an APEX export or AWR report. + +When the user's entry point is a customer-specific APEX application export file, including `.sql` or `.apx`, load this reference before export-only, deployment, or security review references. Treat the export as the first performance/runtime evidence source, ask once for additional customer evidence, and then continue with the available material. + +APEX performance issues often span APEX metadata, APEX runtime logs, browser request behavior, database SQL, and sometimes ORDS/runtime infrastructure. Start by collecting enough APEX context before drawing root-cause conclusions from DB-only evidence. + +## Ask For Evidence + +Ask which files or exports the user can provide and whether the result should be chat-only or saved as an external artifact. Always ask this before substantive analysis, even when the user has already provided one APEX export, AWR report, HAR file, or log and asks to start. For `.sql` or `.apx` APEX application exports, ask this before running static export scans or export-only review. Treat it as an intake question, not a gate: if the user declines more files or no more files are available, continue with the available evidence, finish the analysis, and state the evidence limits. If saved, ask for the output directory or exact file path before substantive analysis. Do not store customer-specific analysis under `apex/admin/` or anywhere else in the skill tree. + +For customer-specific `.sql` or `.apx` APEX application export analysis requests, make the additional-evidence question part of the first user-facing response. Do not run the export scanner, start a static review, draft findings, or create a report until the user has answered, declined, or already stated in the same prompt that no more evidence is available. The first response may also include the static-analysis boundary ("no database access is needed for this step") and the output-location question. + +Do not require all evidence files before beginning; use the available evidence and mark gaps. + +Useful APEX-side evidence: + +- APEX application export for static component review. +- APEX Activity Log or Page Views export for the affected time window, with workspace, application, page, request type, elapsed time, rows queried, session, user, and error metadata. Avoid item values and payload columns unless explicitly needed. +- APEX Builder Page Performance report or supported activity/debug extract for slow pages, regions, processes, Dynamic Actions, and `DEBUG_PAGE_VIEW_ID`. +- APEX Debug export for one narrow user journey, page, session, and time window. +- Browser Network HAR or summarized request list for page load/AJAX count, timings, status codes, and response sizes. Redact cookies, authorization headers, tokens, and request bodies. +- Web Service Activity Log for REST Data Sources or outbound service calls. +- Application Error report for error bursts around the incident. + +Useful DB/ORDS-side evidence, only after asking for DB-skill handoff when interpretation is needed: + +- AWR report for the exact incident window and a comparable healthy baseline window. +- ASH report or ASH extract for sub-hour spikes, top SQL, SQL module/action, session, and wait-event correlation. +- SQL Monitor report or execution plan for named top SQL IDs. +- ORDS logs, pool metrics, or gateway/runtime diagnostics when symptoms mention connection pools, request queues, HTTP errors, or gateway latency. + +## Minimal Intake Questions + +Use short questions, not a long form: + +- What is the affected workspace, application ID, page or user journey, and time window with timezone? +- What symptom is user-visible: slow page load, slow AJAX action, login, export/download, background automation, web service, or intermittent errors? +- Which evidence files are available now: APEX export, Activity/Page Performance extract, Debug, HAR/Network, AWR/ASH, SQL Monitor, ORDS logs? +- Should results stay chat-only, or be written to which external output directory or file path? + +## Analysis Order + +1. Ask once whether additional customer evidence exists for the same case before substantive analysis, and record whether each relevant source is provided, unavailable, absent, declined, or will be added later. If the user declines additional evidence, continue with the available material. +2. If the first step is static file analysis, tell the user before starting that no database connection or live MCP database access is needed for that step. +3. Establish the APEX time window, workspace, application, page/request, user journey, and symptom. +4. Review APEX evidence first: Activity Log, Page Performance, Debug, Browser Network, Web Service Log, Application Errors, and static export signals. +5. If AWR/ASH/SQL Monitor/ORDS evidence is present, ask before switching to the relevant DB or ORDS skill. +6. Correlate DB findings back to APEX modules, page IDs, `/wwv_flow.ajax`, `/wwv_flow.accept`, application aliases, `APP :`, `CLIENT_IDENTIFIER`, or `DEBUG_PAGE_VIEW_ID` when available. +7. Separate proven findings from candidates. AWR evidence can show expensive SQL or waits, but APEX Activity Log or Debug is needed to map that cost to a user-visible APEX path. + +## Connection Boundary + +Static file analysis of APEX exports, AWR HTML/TEXT reports, HAR files, CSV extracts, and logs does not require a database connection. + +Announce that boundary before running the static analysis. If live evidence becomes necessary afterward, stop and ask for the appropriate APEX admin connection or DB-skill handoff before using any database access. + +Live APEX-side evidence gathering through MCP requires the confirmed APEX admin identity from `apex/admin/SKILL.md`: APEX dictionary queries, `APEX_WORKSPACE_ACTIVITY_LOG`, `APEX_DEBUG_MESSAGES`, supported APEX views, APEX debug/error logs, and APEX API checks must not run under `SYS`, `SYSDBA`, parsing schemas, workspace users, ORDS/APEX runtime users, generic deployment users, or unknown accounts. `SYSTEM` is allowed only after the exact uppercase `YES` confirmation required by the APEX Admin Identity Gate. + +Ask for an explicit DB-skill handoff and that DB skill's required connection/user when the next step needs live generic database or ORDS evidence, such as `DBA_HIST_ACTIVE_SESS_HISTORY`, `V$SQL`, `DBMS_XPLAN`, object/index/statistics inspection, grants, parameter checks, or ORDS pool/runtime diagnostics. Do not reuse the APEX admin connection for this handoff unless the selected DB skill explicitly accepts it. + +## Privacy Guardrails + +- Do not request or print passwords, tokens, cookies, authorization headers, wallet secrets, or credential values. +- Prefer metadata exports over payload exports. +- Redact usernames, IP addresses, hostnames, URLs, request values, SQL text, or object names when they are not needed for the user's decision. +- Keep customer-specific paths, file names, line references, application names, SQL IDs, object names, and findings only in the confirmed external analysis artifact and chat summary. diff --git a/apex/admin/references/monitoring/awr-wait-correlation.md b/apex/admin/references/monitoring/awr-wait-correlation.md new file mode 100644 index 0000000..9bd696a --- /dev/null +++ b/apex/admin/references/monitoring/awr-wait-correlation.md @@ -0,0 +1,68 @@ +# APEX Cross-Check With AWR Wait Events + +Use this reference only after APEX activity has identified the workspace, application, page, and time window. + +For broad APEX application performance analysis, load `apex-performance-evidence.md` first to ask for available APEX, browser, AWR/ASH, SQL Monitor, and ORDS evidence and the output path for customer-specific results. + +## Scope + +APEX activity chooses the incident window. Generic AWR, ASH, and wait-event interpretation belongs to DB performance skills. + +If the user attaches or references an AWR report, ASH extract, wait-event output, SQL Monitor report, execution plan, `V$`/`DBA_HIST` output, or ORDS pool/runtime diagnostics, stop before interpreting it and ask whether to switch to the relevant DB skill. Continue only after the user confirms. Use the selected DB skill's required connection/user for any live DB follow-up; do not reuse the APEX admin connection unless the DB skill explicitly accepts it. + +Use this handoff only after confirmation: + +```text +DB skill in use: db/performance/awr-reports.md, db/performance/ash-analysis.md, or db/performance/wait-events.md for generic database performance interpretation. The APEX monitoring skill is being used for choosing the APEX workspace, application, page, session, request, and time window. +``` + +After this handoff, use a diagnostics/performance account suitable for AWR, ASH, `DBA_HIST`, `V$`, SQL Monitor, or execution-plan evidence according to the selected DB skill. + +## Historical Wait Cross-Check + +```sql +WITH snaps AS ( + SELECT snap_id, + dbid, + instance_number, + begin_interval_time, + end_interval_time + FROM dba_hist_snapshot + WHERE begin_interval_time >= SYSTIMESTAMP - INTERVAL '1' DAY +), +waits AS ( + SELECT s.begin_interval_time, + s.end_interval_time, + e.instance_number, + e.wait_class, + e.event_name, + e.total_waits, + e.time_waited_micro + - LAG(e.time_waited_micro) OVER ( + PARTITION BY e.dbid, e.instance_number, e.event_id + ORDER BY e.snap_id) AS waited_micro_delta + FROM dba_hist_system_event e + JOIN snaps s + ON s.snap_id = e.snap_id + AND s.dbid = e.dbid + AND s.instance_number = e.instance_number + WHERE e.wait_class <> 'Idle' +) +SELECT begin_interval_time, + end_interval_time, + instance_number, + wait_class, + event_name, + ROUND(waited_micro_delta / 1000000, 2) AS waited_seconds +FROM waits +WHERE waited_micro_delta > 0 +ORDER BY begin_interval_time DESC, + waited_seconds DESC +FETCH FIRST 50 ROWS ONLY; +``` + +## Guardrails + +- AWR and ASH require Diagnostics Pack in production. +- Database waits during an APEX window are correlation evidence, not proof of a page or region root cause. +- Confirm with SQL ID, ECID, module/action, client identifier, APEX debug, Page Performance reports, or application instrumentation. diff --git a/apex/admin/references/monitoring/background-jobs.md b/apex/admin/references/monitoring/background-jobs.md new file mode 100644 index 0000000..aa30e72 --- /dev/null +++ b/apex/admin/references/monitoring/background-jobs.md @@ -0,0 +1,88 @@ +# APEX Background Job Monitoring + +Use this reference for APEX background processing, automations, scheduled work, `APEX_AUTOMATION_LOG`, `APEX_AUTOMATION_MSG_LOG`, and any installed public APEX scheduler/job views discovered in the target environment. + +Version check: use `ALL_OBJECTS` and `ALL_TAB_COLUMNS` before assuming APEX job-log or automation view availability. + +Use APEX Diff as a convenience helper to compare background-job, automation, +and public APEX API availability across releases before selecting standard +monitoring calls, including current releases such as APEX 26.1 when they are +listed there. Verify the target instance locally with `APEX_DICTIONARY`, +`ALL_OBJECTS`, `ALL_TAB_COLUMNS`, and `ALL_ARGUMENTS`: + +```text +https://apexadb.oracle.com/ords/r/apexdiff/apex_diff/home +``` + +## Job Log Pre-Check + +```sql +SELECT owner, + object_name, + object_type +FROM all_objects +WHERE object_name IN ( + 'APEX_AUTOMATION_LOG', + 'APEX_AUTOMATION_MSG_LOG', + 'APEX_APPL_AUTOMATIONS', + 'APEX_APPLICATIONS') + OR object_name LIKE 'APEX%SCHEDULER%JOB%' +ORDER BY object_name, + owner; +``` + +```sql +SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name IN ( + 'APEX_AUTOMATION_LOG', + 'APEX_AUTOMATION_MSG_LOG', + 'APEX_APPL_AUTOMATIONS', + 'APEX_APPLICATIONS') + OR table_name LIKE 'APEX%SCHEDULER%JOB%' +ORDER BY table_name, + column_id; +``` + +If automation log views are missing, use APEX Builder automation/task reports, application debug logs, application-specific job tables, and database scheduler views. Do not query internal APEX repository tables as a workaround. + +## Recent APEX Job Failures + +Adapt column names to the installed view. + +```sql +SELECT workspace, + application_id, + automation_id, + automation_static_id, + automation_name, + is_job, + status, + status_code, + start_timestamp, + end_timestamp, + successful_row_count, + error_row_count +FROM apex_automation_log +WHERE start_timestamp >= SYSTIMESTAMP - INTERVAL '1' DAY + AND status_code <> 'SUCCESS' +ORDER BY start_timestamp DESC +FETCH FIRST 50 ROWS ONLY; +``` + +For a specific automation log entry, inspect `APEX_AUTOMATION_MSG_LOG` columns first, then collect only narrow message excerpts for the affected `AUTOMATION_LOG_ID`. + +## Scheduler Mapping + +Use APEX job name, application ID, parsing schema, and run timestamp to map APEX symptoms to `DBA_SCHEDULER_JOB_RUN_DETAILS`. Treat this as correlation until confirmed with job action, comments, module/action, or application code. + +Do not blindly call `DBMS_SCHEDULER.RUN_JOB`, `STOP_JOB`, `DISABLE`, `ENABLE`, or `DROP_JOB`. Show affected job, state, recent runs, and likely impact first; ask for confirmation before changing job state. + +## DB Skill Usage + +DB skill in use: `db/features/dbms-scheduler.md` for generic `DBMS_SCHEDULER` job design, attributes, logging levels, `max_failures`, `max_run_duration`, job classes, and operational management. The APEX monitoring skill is being used for APEX application, workspace, automation, and job-log context. + +After this handoff, use the DB skill's required connection/user for live `DBMS_SCHEDULER` inspection or job-state changes. Do not reuse the APEX admin connection unless the DB skill explicitly accepts it. diff --git a/apex/admin/references/monitoring/error-handling.md b/apex/admin/references/monitoring/error-handling.md new file mode 100644 index 0000000..8db84a1 --- /dev/null +++ b/apex/admin/references/monitoring/error-handling.md @@ -0,0 +1,106 @@ +# APEX Error Handling And Logging + +Use this reference for collecting, categorizing, and prioritizing APEX errors from `APEX_WORKSPACE_ACTIVITY_LOG`, `APEX_DEBUG_MESSAGES`, App Builder error reports, and APEX activity logs. For documented instance-admin debug procedures such as `APEX_INSTANCE_DEBUG.LIST_PAGE_VIEWS` or `APEX_INSTANCE_DEBUG.LIST_MESSAGES`, use `instance-debug-api.md`. + +Version check: use `APEX_DICTIONARY` and `ALL_TAB_COLUMNS` before assuming APEX debug, activity, or error-report view availability. + +## Error Log Pre-Check + +```sql +SELECT view_name, + comments +FROM apex_dictionary +WHERE view_name IN ( + 'APEX_WORKSPACE_ACTIVITY_LOG', + 'APEX_ACTIVITY_LOG', + 'APEX_DEBUG_MESSAGES') + OR view_name LIKE '%ERROR%' +ORDER BY view_name; +``` + +```sql +SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name IN ( + 'APEX_WORKSPACE_ACTIVITY_LOG', + 'APEX_ACTIVITY_LOG', + 'APEX_DEBUG_MESSAGES') +ORDER BY table_name, + column_id; +``` + +Use `APEX_WORKSPACE_ACTIVITY_LOG`, `APEX_DEBUG_MESSAGES`, App Builder error reports, ORDS/web-server logs, and application-specific error tables. Do not query internal APEX repository tables as a workaround. + +## Collection And Priority + +```sql +SELECT workspace, + application_id, + application_name, + page_id, + page_name, + error_on_component_type, + error_on_component_name, + COUNT(*) AS error_events, + COUNT(DISTINCT apex_session_id) AS affected_sessions, + COUNT(DISTINCT apex_user) AS affected_users, + MIN(view_date) AS first_seen, + MAX(view_date) AS last_seen, + SUBSTR(MIN(error_message), 1, 300) AS sample_error +FROM apex_workspace_activity_log +WHERE view_date >= SYSDATE - 1 + AND error_message IS NOT NULL +GROUP BY workspace, + application_id, + application_name, + page_id, + page_name, + error_on_component_type, + error_on_component_name +ORDER BY error_events DESC, + affected_sessions DESC, + last_seen DESC; +``` + +Classify errors as authentication/authorization, validation/business rule, SQL/PLSQL, ORDS/REST/integration, timeout/performance, or internal/unhandled. Prioritize by production impact, affected users/sessions, recency, security risk, data-loss risk, and critical workflow impact. + +## Debug Correlation + +```sql +SELECT message_timestamp, + application_id, + page_id, + session_id, + page_view_id, + apex_user, + message_level, + SUBSTR(message, 1, 300) AS message_sample +FROM apex_debug_messages +WHERE message_timestamp >= :apex_start_time + AND message_timestamp < :apex_end_time + AND (:application_id IS NULL OR application_id = :application_id) + AND (:page_view_id IS NULL OR page_view_id = :page_view_id) +ORDER BY message_timestamp; +``` + +Use `APEX_WORKSPACE_ACTIVITY_LOG.DEBUG_PAGE_VIEW_ID` to find the corresponding `APEX_DEBUG_MESSAGES.PAGE_VIEW_ID`. Prefer page view ID, `APEX_SESSION_ID`, ECID, application/page, APEX user, and timestamp window. Avoid verbose production debug unless scoped and temporary. + +## Quick Fix Patterns + +- Missing grant, synonym, or invalid object: confirm parsing schema and least-privilege object grants. +- Bad bind or item conversion: align APEX item type, format mask, NLS assumptions, and database column type. +- Unhandled process exception: log correlation metadata and return a safe user-facing message. +- Auth/authz misconfiguration: review authorization scheme placement, public pages, and session state protection. +- REST credential/token expiry: rotate via APEX Web Credentials; never print credential values or bearer tokens. +- Timeout from slow SQL or remote call: narrow APEX page/component/time window first. + +## DB Skill Usage + +DB skill in use: `db/security/auditing.md` for generic database audit trails. DB skill in use: `db/performance/awr-reports.md` and `db/performance/ash-analysis.md` for AWR/ASH correlation. DB skill in use: `db/monitoring/alert-log-analysis.md` for database alert log, trace, and ADR investigation. The APEX monitoring skill is being used for APEX debug/error context and incident time-window selection. + +After a DB-skill handoff, use the selected DB skill's required connection/user. Do not reuse the APEX admin connection for live AWR, ASH, `V$`, `DBA_HIST`, alert-log, trace, ADR, audit-policy, or grant investigation unless the DB skill explicitly accepts that identity. + +AWR and ASH require Diagnostics Pack in production. diff --git a/apex/admin/references/monitoring/export-runtime-risk-review.md b/apex/admin/references/monitoring/export-runtime-risk-review.md new file mode 100644 index 0000000..3be29d8 --- /dev/null +++ b/apex/admin/references/monitoring/export-runtime-risk-review.md @@ -0,0 +1,78 @@ +# APEX Export Runtime Risk Review + +Use this reference for static APEX export review when the user asks whether an APEX application can create runtime pressure, slow pages, many AJAX requests, or long-running APEX requests. + +This is APEX-only. Do not tune ORDS connection pools, SQLcl, database instance settings, indexes, wait events, or execution plans here. If the evidence points there, record a clear external handoff and keep the APEX finding separate. + +When the entry point is a customer-specific APEX application export file, including `.sql` or `.apx`, load `apex-performance-evidence.md` first and ask once for additional evidence before running this static export runtime-risk review. + +Before running this static export review or the export risk scan tool, tell the user that no database connection or live MCP database access is needed for this step. For customer exports, ask whether the result should stay chat-only or be saved to a user-confirmed external output path outside the skill tree. + +If the user provides only an APEX export for performance or runtime analysis, ask once whether they also have runtime evidence such as APEX Activity Log/Page Performance, APEX Debug, HAR/Network, AWR/ASH, SQL Monitor, or ORDS logs for the same case. If the user declines or no more files are available, continue with export-only analysis and state that runtime impact remains unverified without those sources. + +Version check: APEX export syntax and component attributes are version-specific. Read the export header first and treat missing attributes as version or component differences, not as proof that the behavior is absent. + +## Export Header + +Capture only non-secret metadata from the export header: + +- APEX export release, for example `p_release`. +- Application ID and application name. +- Export timestamp. +- Application version, for example `p_flow_version`. +- Compatibility mode, for example `p_compatibility_mode`. +- Counts for pages, regions, processes, validations, buttons, Dynamic Actions, plug-ins, and messages. + +## Static APEX Risk Signals + +Search the export for APEX patterns that can make requests longer or multiply server calls: + +```text +apex_collection +APEX_COLLECTION +p_wait_for_result=>'Y' +NATIVE_EXECUTE_PLSQL_CODE +p_ajax_items_to_submit +Dynamic Actions +COMMIT; +EXECUTE IMMEDIATE +DBMS_LOB.CREATETEMPORARY +HTP.P +apex_web_service +APEX_APPLICATION.G_X +SELECT * +``` + +Interpret these as candidates, not proof. A static export can identify likely APEX hot spots, but runtime evidence is still needed to rank impact. + +## APEX-Only Findings + +For each candidate, record: + +- Page ID and page name. +- Component type: region, process, Dynamic Action, validation, computation, plug-in, or shared component. +- Why it is APEX-relevant: repeated AJAX call, synchronous PL/SQL action, Collection materialization, large report/chart refresh, CLOB/JSON response, explicit commit in Page Processing, or external webservice call from an APEX request. +- User-facing path if visible from names or comments. +- Verification target in APEX: Activity Log, Page Performance, Debug, component settings, or browser Network tab for APEX requests. + +## Runtime Verification Inside APEX + +Use APEX-native evidence first: + +- APEX Activity Log: page, session, request, elapsed time, rows queried, errors, and AJAX/request patterns. +- Page Performance reports: slowest pages, regions, processes, and component timing. +- APEX Debug for a narrow test window and one affected user journey. +- Browser Network tab to count APEX page and AJAX requests and response sizes. + +Avoid exporting debug CLOBs, request payloads, item values, uploaded files, or secret-bearing URLs unless the user explicitly confirms the need. + +## External Handoff Boundary + +When the likely symptom is described as connection pool growth, waits, SQL elapsed time, scheduler pressure, or instance/resource pressure, keep the APEX result in this form: + +```text +APEX finding: page/component/request pattern and why it can lengthen or multiply APEX requests. +External handoff: ORDS/database/runtime team should validate pool/session/SQL/wait evidence for the same time window. +``` + +Do not recommend changing ORDS pool size from this skill. At most, say whether APEX evidence suggests reducing long-running or excessive APEX requests before any external pool tuning is considered. diff --git a/apex/admin/references/monitoring/instance-debug-api.md b/apex/admin/references/monitoring/instance-debug-api.md new file mode 100644 index 0000000..ee10574 --- /dev/null +++ b/apex/admin/references/monitoring/instance-debug-api.md @@ -0,0 +1,145 @@ +# APEX Instance Debug API + +Use this reference when an APEX instance administrator needs the documented `APEX_INSTANCE_DEBUG` API for instance-level debug enablement checks, recent debug page views, activity log output, or messages for a known page view ID. + +Official source: Oracle APEX 26.1 API Reference, `APEX_INSTANCE_DEBUG`: + +```text +https://docs.oracle.com/en/database/oracle/apex/26.1/aeapi/APEX_INSTANCE_DEBUG.html +``` + +This reference is for supported APEX debug APIs only. It does not replace browser reproduction, Workspace Monitor Activity, SQL-backed view discovery, or DB/ORDS diagnostics. + +## API Surface + +`APEX_INSTANCE_DEBUG` exposes these documented APIs: + +- `APEX_INSTANCE_DEBUG.ENABLE` +- `APEX_INSTANCE_DEBUG.DISABLE` +- `APEX_INSTANCE_DEBUG.IS_ENABLED` +- `APEX_INSTANCE_DEBUG.LIST_ACTIVITY` +- `APEX_INSTANCE_DEBUG.LIST_MESSAGES` +- `APEX_INSTANCE_DEBUG.LIST_PAGE_VIEWS` + +Use `ENABLE` and `DISABLE` as state-changing instance debug operations. Use `IS_ENABLED`, `LIST_ACTIVITY`, `LIST_MESSAGES`, and `LIST_PAGE_VIEWS` for narrow debug status and evidence collection. + +## Guardrails + +- Apply the APEX Admin Identity Gate from `apex/admin/SKILL.md` before using this API through MCP or SQLcl. +- Create or update the local protocol file from `../debugging/protocol-file.md` before enabling debug, disabling debug, or collecting customer-specific debug evidence. +- Do not enable instance debug broadly in production. Require explicit user confirmation, target workspace/application/page/user/session when known, and a short time window. +- Always check whether instance debug is already enabled before changing it. +- After investigation, recommend or perform `APEX_INSTANCE_DEBUG.DISABLE` only after the user confirms the state-changing action unless the same approved workflow explicitly includes cleanup. +- Treat all output as sensitive. Debug and activity output may contain user names, IP addresses, URLs, component names, SQL, bind values, item values, error text, or operational metadata. +- Prefer metadata and focused excerpts. Do not paste full debug dumps into chat. + +## Status Check + +Use this before enabling or disabling instance debug: + +```sql +BEGIN + IF apex_instance_debug.is_enabled THEN + dbms_output.put_line('APEX instance debug is enabled.'); + ELSE + dbms_output.put_line('APEX instance debug is disabled.'); + END IF; +END; +/ +``` + +## Enable Or Disable + +Enable instance debug only after the scope and confirmation are recorded in the protocol file: + +```sql +BEGIN + apex_instance_debug.enable; + COMMIT; +END; +/ +``` + +Disable instance debug after the investigation or during cleanup: + +```sql +BEGIN + IF apex_instance_debug.is_enabled THEN + apex_instance_debug.disable; + COMMIT; + END IF; +END; +/ +``` + +## List Recent Activity + +Use `LIST_ACTIVITY` for recent activity log entries when a narrow filter is available: + +```sql +BEGIN + apex_instance_debug.list_activity( + p_from_date => :from_date, + p_to_date => :to_date, + p_app_id => :application_id, + p_page_id => :page_id, + p_workspace_name => :workspace_name, + p_session_id => :session_id, + p_user => :apex_user, + p_error => :error_like, + p_debug => :max_debug_level); +END; +/ +``` + +Keep filters as specific as the case allows. Use `p_error => '%'` only when the user is investigating errors and the time window is narrow. + +## List Debug Page Views + +Use `LIST_PAGE_VIEWS` to find recent debug-enabled page views, optionally for a known APEX session: + +```sql +BEGIN + apex_instance_debug.list_page_views( + p_session_id => :session_id, + p_max_rows => 30, + p_show_d2 => FALSE); +END; +/ +``` + +Keep `p_max_rows` small by default. Increase it only when the user confirms the broader evidence need. + +## List Messages For A Page View + +Use `LIST_MESSAGES` only after a relevant page view ID is known: + +```sql +BEGIN + apex_instance_debug.list_messages( + p_page_view_id => :page_view_id); +END; +/ +``` + +Summarize the result and quote only the smallest necessary excerpt. Do not include full SQL text, bind values, item values, cookies, tokens, request bodies, or secret-bearing URLs unless the user explicitly confirms the need and the output remains local. + +## Routing + +- Browser reproduction, console, and network metadata: `../debugging/live-browser-debugging.md`. +- Workspace Monitor Activity, Active Sessions, Debug/Trace UI controls: `workspace-monitor-activity.md`. +- SQL-backed error/debug correlation with supported public views: `error-handling.md`. +- Page and request timing analysis: `page-performance.md` and `activity-log.md`. +- AWR, ASH, SQL Monitor, wait events, execution plans, ORDS pool diagnostics, or infrastructure traces: route to the DB/ORDS skill. + +## Output + +Record the following in the protocol file: + +- API used and whether it was read-only or state-changing; +- identity gate result; +- workspace, application, page, user, session, and time window; +- debug state before and after the workflow when checked; +- page view IDs and correlation IDs; +- redaction decisions; +- DB/ORDS/APEXlang handoffs. diff --git a/apex/admin/references/monitoring/ir-ig-tuning.md b/apex/admin/references/monitoring/ir-ig-tuning.md new file mode 100644 index 0000000..0d3fd5d --- /dev/null +++ b/apex/admin/references/monitoring/ir-ig-tuning.md @@ -0,0 +1,77 @@ +# Interactive Report And Grid Tuning + +Use this reference for APEX Interactive Report and Interactive Grid performance: filtering, sorting, pagination, downloads, report settings, SQL IDs, and AWR correlation. + +Version check: use `APEX_DICTIONARY` and `ALL_TAB_COLUMNS` before assuming Interactive Report or Interactive Grid metadata view availability. + +Use APEX Diff as a convenience helper to compare IR/IG metadata views and +standard APEX monitoring surfaces across releases before choosing metadata or +performance queries, including current releases such as APEX 26.1 when they are +listed there. Verify the installed target locally with `APEX_DICTIONARY`, +`ALL_OBJECTS`, and `ALL_TAB_COLUMNS`: + +```text +https://apexadb.oracle.com/ords/r/apexdiff/apex_diff/home +``` + +## Region Metadata Pre-Check + +```sql +SELECT owner, + object_name, + object_type +FROM all_objects +WHERE object_name IN ( + 'APEX_APPLICATION_PAGE_REGIONS', + 'APEX_APPLICATION_PAGE_IR', + 'APEX_APPLICATION_PAGE_IR_COL', + 'APEX_APPL_PAGE_IGS', + 'APEX_APPL_PAGE_IG_COLUMNS', + 'APEX_WORKSPACE_ACTIVITY_LOG', + 'APEX_DEBUG_MESSAGES') +ORDER BY object_name, + owner; +``` + +```sql +SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name IN ( + 'APEX_APPLICATION_PAGE_REGIONS', + 'APEX_APPLICATION_PAGE_IR', + 'APEX_APPLICATION_PAGE_IR_COL', + 'APEX_APPL_PAGE_IGS', + 'APEX_APPL_PAGE_IG_COLUMNS') +ORDER BY table_name, + column_id; +``` + +## Runtime Symptoms + +Use activity logs to identify whether the pain is initial render, filtering, sorting, pagination, aggregation, save, or download. + +Red flags: + +- Filtering is slow only for wildcard, case-insensitive, or contains searches. +- Pagination is slow because the region query must sort or count a large rowset before returning the next page. +- Download is slow because it bypasses small-page pagination and exports a much larger result set. +- User-saved reports add expensive filters, control breaks, aggregates, highlights, or computations. + +## APEX-Specific Checks + +- Avoid unnecessary columns in IR/IG source SQL. Wide projections increase sort, download, network, and browser cost. +- Keep bind variable types aligned with table column types. APEX item values are strings; avoid implicit conversions. +- Prefer server-side filters with bind variables over concatenating item values into dynamic SQL. +- Limit download scope and require deliberate user action for large exports. +- For IG pages with DML, validate that any new index does not make saves unacceptably slow. + +## DB Skill Usage + +DB skill in use: `db/sql-dev/sql-tuning.md` for generic SQL tuning. DB skill in use: `db/performance/index-strategy.md` for index design. DB skill in use: `db/monitoring/top-sql-queries.md` for SQL IDs and `DBA_HIST_SQLSTAT`. DB skill in use: `db/performance/awr-reports.md` for AWR interpretation. The APEX monitoring skill is being used for IR/IG behavior, report settings, request patterns, and APEX page context. + +After a DB-skill handoff, use the selected DB skill's required connection/user, such as a diagnostics/performance account for AWR, ASH, `DBA_HIST`, `V$`, SQL Monitor, or execution-plan evidence and a schema/object owner or scoped tuning identity when the DB tuning skill requires object-level inspection. Do not reuse the APEX admin connection unless the DB skill explicitly accepts it. + +AWR, ASH, and `DBA_HIST_SQLSTAT` require Diagnostics Pack in production. diff --git a/apex/admin/references/monitoring/mcp-availability.md b/apex/admin/references/monitoring/mcp-availability.md new file mode 100644 index 0000000..528bfcb --- /dev/null +++ b/apex/admin/references/monitoring/mcp-availability.md @@ -0,0 +1,105 @@ +# APEX MCP Availability Guard + +Use this topic when an APEX workflow depends on database access through an MCP tool, for example listing workspaces, creating a workspace, checking `APEX_RELEASE`, checking `APEX_PATCHES`, or querying APEX runtime views. + +This is an APEX workflow guard, not database-client troubleshooting. Do not provide setup commands, client configuration advice, or connection-store instructions from this topic. + +## When To Check + +Before any APEX workflow that will run SQL or PL/SQL through MCP: + +- Confirm the MCP tool transport is available. +- Confirm a database connection can be established or is already active. +- Confirm the active connection is the intended APEX admin identity before running APEX-owned live checks, including read-only checks. +- If the APEX workflow needs a specific connection name, confirm that connection before generating SQL. + +Use the smallest available client-side MCP check. Do not run APEX DDL, APEX administration APIs, generic DB diagnostics, or destructive SQL as a connectivity test. + +## Stop Condition + +If the MCP tool reports a closed transport, unavailable server, disconnected tool channel, or similar client-side transport failure, stop the APEX workflow. Do not infer database state from stale context, screenshots, previous outputs, or another UI session. + +Use this message: + +```text +APEX MCP availability check failed: the MCP transport is closed, so I cannot safely verify or change APEX state from here. I will pause the APEX workflow until the MCP tool channel is available again. +``` + +If the user has APEX open in a browser, make clear that this does not prove the MCP tool channel is available: + +```text +Your APEX browser session may still be connected, but this APEX workflow needs the MCP tool channel. Those are separate sessions, and I cannot use browser state as confirmation for database changes. +``` + +## Recovery Behavior + +After the user says MCP is available again: + +1. Repeat the MCP availability check. +2. Reconnect or confirm the active database connection is the intended APEX admin identity. +3. Re-read APEX state from the database. +4. If an APEX provisioning workflow may have been interrupted after create steps, inventory each planned artifact individually with `references/workspace/lifecycle.md#provisioning-recovery-after-interruption`. +5. Ask whether the user wants to roll back the listed artifacts before continuing or retrying. +6. Continue only from freshly verified state. + +Never continue a workspace create, user create, patch check, or removal workflow from pre-failure assumptions. + +## APEX State To Re-Read + +Pick the smallest relevant verification query after MCP recovers: + +```sql +SELECT version_no, + CASE + WHEN REGEXP_LIKE(version_no, '^(26\.1|24\.2|24\.1)(\.|$)') + THEN 'SUPPORTED' + ELSE 'UNSUPPORTED' + END AS apex_admin_skill_support +FROM apex_release; +``` + +If the recovered `APEX_ADMIN_SKILL_SUPPORT` value is `UNSUPPORTED`, stop the +APEX workflow and use the unsupported-version safety message from +`references/security/safety-messages.md`. + +```sql +SELECT workspace_id, + workspace, + schemas, + applications, + apex_developers, + apex_workspace_administrators +FROM apex_workspaces +ORDER BY workspace; +``` + +For user provisioning recovery: + +```sql +SELECT workspace_name, + user_name, + email, + is_admin, + is_application_developer, + account_locked +FROM apex_workspace_apex_users +WHERE workspace_name = :workspace_name + AND user_name = :user_name; +``` + +For interrupted workspace/app provisioning, use the lifecycle recovery checklist to re-read the planned workspace, schema mappings, APEX users, database users, application tables, and APEX applications one by one before asking: + +```text +I found the following artifacts from the interrupted APEX provisioning workflow: . Do you want me to roll back the listed artifacts by removing only these objects? +``` + +## DB Skill Usage + +No DB skill is used for this topic. This topic only decides whether an APEX workflow may continue when MCP-backed database access is unavailable. + +## Guardrails + +- Do not continue an APEX workflow after `Transport closed` because a previous query succeeded. +- Do not treat a browser APEX session as proof that MCP database access is available. +- Do not re-run a create step without first checking whether the object was committed before the transport failed. +- Do not explain database-client internals when the user only needs an APEX workflow stop/retry decision. diff --git a/apex/admin/references/monitoring/page-performance.md b/apex/admin/references/monitoring/page-performance.md new file mode 100644 index 0000000..2ea0931 --- /dev/null +++ b/apex/admin/references/monitoring/page-performance.md @@ -0,0 +1,92 @@ +# APEX Page Performance Profiler + +Use this reference for the slowest APEX pages, regions, APEX Builder Page Performance reports, supported APEX activity/debug views, and `DBA_HIST_SQLSTAT` correlation. + +For broad APEX application performance analysis, load `apex-performance-evidence.md` first to ask for available APEX, browser, AWR/ASH, SQL Monitor, and ORDS evidence and the output path for customer-specific results. + +Version check: use `APEX_DICTIONARY` and `ALL_TAB_COLUMNS` before assuming activity-log, page-view, page-performance, or debug view availability. Do not hard-code internal or undocumented APEX repository view names. + +Use APEX Diff as a convenience helper to compare page-view, activity-log, +debug-message, and related monitoring views across APEX releases before +choosing standard monitoring calls, including current releases such as APEX +26.1 when they are listed there. Verify the target instance locally with +`APEX_DICTIONARY` and `ALL_TAB_COLUMNS` before generating final SQL: + +```text +https://apexadb.oracle.com/ords/r/apexdiff/apex_diff/home +``` + +## Logging Pre-Check + +Page performance and debug logging can increase log volume and may capture sensitive context. Enable or increase it only for the affected application, workspace, or test window when possible. + +```sql +SELECT view_name, + comments +FROM apex_dictionary +WHERE view_name IN ( + 'APEX_WORKSPACE_ACTIVITY_LOG', + 'APEX_ACTIVITY_LOG', + 'APEX_DEBUG_MESSAGES') + OR view_name LIKE '%PAGE%VIEW%' + OR view_name LIKE '%PAGE%PERFORMANCE%' +ORDER BY view_name; +``` + +```sql +SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name IN ( + 'APEX_WORKSPACE_ACTIVITY_LOG', + 'APEX_ACTIVITY_LOG', + 'APEX_DEBUG_MESSAGES') +ORDER BY table_name, + column_id; +``` + +## Slowest Pages + +```sql +SELECT workspace, + application_id, + application_name, + page_id, + page_name, + COUNT(*) AS page_events, + COUNT(DISTINCT apex_session_id) AS apex_sessions, + ROUND(AVG(elapsed_time), 3) AS avg_elapsed_seconds, + ROUND(PERCENTILE_CONT(0.95) + WITHIN GROUP (ORDER BY elapsed_time), 3) AS p95_elapsed_seconds, + MAX(elapsed_time) AS max_elapsed_seconds, + MIN(view_date) AS first_seen, + MAX(view_date) AS last_seen +FROM apex_workspace_activity_log +WHERE view_date >= SYSDATE - 1 +GROUP BY workspace, + application_id, + application_name, + page_id, + page_name +HAVING COUNT(*) >= 10 +ORDER BY p95_elapsed_seconds DESC +FETCH FIRST 20 ROWS ONLY; +``` + +Use APEX Builder Page Performance reports or narrow SQL/CSV extracts of page, region, elapsed time, session, `DEBUG_PAGE_VIEW_ID`, and timestamp metadata. Do not export debug CLOBs, request values, item payloads, or file payloads unless explicitly confirmed. + +## DB Skill Usage + +If the user provides AWR, ASH, SQL Monitor, execution plans, `DBA_HIST_SQLSTAT`, wait-event output, `V$` output, or ORDS runtime diagnostics, ask before switching to the DB skill. Do not interpret that evidence inside this APEX monitoring reference, and do not reuse the APEX admin connection for live DB-skill work unless the DB skill explicitly accepts it. + +Use this handoff only after confirmation: + +```text +DB skill in use: db/monitoring/top-sql-queries.md or db/performance/awr-reports.md for generic database performance interpretation. The APEX monitoring skill is being used for page, region, session, request, and time-window context. +``` + +After this handoff, use the selected DB skill's required connection/user, such as a diagnostics/performance account for `DBA_HIST_SQLSTAT`, AWR, ASH, `V$`, SQL Monitor, or execution-plan evidence. + +AWR, ASH, and `DBA_HIST_SQLSTAT` require Diagnostics Pack in production. diff --git a/apex/admin/references/monitoring/rest-data-sources.md b/apex/admin/references/monitoring/rest-data-sources.md new file mode 100644 index 0000000..ea25e20 --- /dev/null +++ b/apex/admin/references/monitoring/rest-data-sources.md @@ -0,0 +1,66 @@ +# APEX REST Data Source Health Check + +Use this reference for APEX REST Data Sources, Web Source Modules, REST Source Synchronization, `APEX_WEBSERVICE_LOG`, latency, HTTP status codes, and component impact. + +Version check: use `APEX_DICTIONARY` and `ALL_TAB_COLUMNS` before assuming REST Data Source, Web Source, or webservice-log view availability. + +## REST Source Inventory + +```sql +SELECT view_name, + comments +FROM apex_dictionary +WHERE view_name LIKE 'APEX%WEB%SRC%' + OR view_name LIKE 'APEX%REST%SOURCE%' + OR view_name LIKE 'APEX%WEBSERVICE%LOG%' +ORDER BY view_name; +``` + +```sql +SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name IN ( + 'APEX_APPL_WEB_SRC_MODULES', + 'APEX_APPL_WEB_SRC_OPERATIONS', + 'APEX_APPL_WEB_SRC_PARAMETERS', + 'APEX_WEBSERVICE_LOG', + 'APEX_REST_SOURCE_SYNC_LOG') +ORDER BY table_name, + column_id; +``` + +Do not print credentials, authorization headers, API keys, OAuth tokens, or full URLs with secrets. + +## Latency And Error Codes + +Use `APEX_WEBSERVICE_LOG` when available. Inspect installed columns before selecting status-code or elapsed-time fields. + +```sql +SELECT application_id, + rest_source_id, + status_code, + COUNT(*) AS calls, + ROUND(AVG(elapsed_sec), 3) AS avg_elapsed_seconds, + MAX(elapsed_sec) AS max_elapsed_seconds, + MIN(request_date) AS first_seen, + MAX(request_date) AS last_seen +FROM apex_webservice_log +WHERE request_date >= SYSTIMESTAMP - INTERVAL '1' DAY +GROUP BY application_id, + rest_source_id, + status_code +ORDER BY max_elapsed_seconds DESC; +``` + +Map symptoms back to APEX pages and components with `APEX_WORKSPACE_ACTIVITY_LOG`. Decide whether the issue is global to a remote service or isolated to a component, operation, parameter set, or page request. + +## DB Skill Usage + +DB skill in use: `db/ords/ords-monitoring.md` for generic ORDS monitoring and request/pool troubleshooting. DB skill in use: `db/performance/ash-analysis.md` and `db/performance/wait-events.md` for `DBA_HIST_ACTIVE_SESS_HISTORY`, `V$ACTIVE_SESSION_HISTORY`, wait-class, and network-wait interpretation. The APEX monitoring skill is being used for REST Data Source metadata, APEX webservice logs, and component impact. + +After a DB/ORDS-skill handoff, use the selected skill's required connection/user, such as an ORDS/runtime administration identity for ORDS pool diagnostics or a diagnostics/performance account for ASH, `DBA_HIST`, `V$`, and wait-event evidence. Do not reuse the APEX admin connection unless the DB/ORDS skill explicitly accepts it. + +ASH and `DBA_HIST_ACTIVE_SESS_HISTORY` require Diagnostics Pack in production. diff --git a/apex/admin/references/monitoring/security-review.md b/apex/admin/references/monitoring/security-review.md new file mode 100644 index 0000000..106f7b0 --- /dev/null +++ b/apex/admin/references/monitoring/security-review.md @@ -0,0 +1,15 @@ +# APEX Monitoring Security Review + +Use this checklist after substantial APEX monitoring, replay, debug, error-log, performance, REST, or background-job work. + +- Scope: APEX logs, debug context, Session Replay output, page/runtime context, workspace/application/page IDs, and time windows stayed in this skill; generic AWR, ASH, wait-event, SQL tuning, ORDS, scheduler, auditing, or alert-log analysis was routed to `db/...`. +- DB usage messages: every generic DB step has a visible `DB skill in use:` message naming the relevant DB skill path. +- APEX admin identity: every live MCP-backed APEX monitoring step used the confirmed APEX admin identity, not `SYS`, `SYSDBA`, a parsing schema, workspace user, ORDS/APEX runtime account, generic deployment user, or unknown account. If `SYSTEM` was used, the exact uppercase `YES` confirmation, scope, targets, and risk summary were recorded before monitoring continued. +- Protocol file: every debugging workflow, including browser-guided debugging, created or updated a local protocol file outside the skill tree before reproduction, Debug/Trace, SQL-backed monitoring, or state-changing actions began. +- DB handoff identity: every generic DB/ORDS/performance step used the selected DB skill's required connection/user rather than silently reusing the APEX admin connection. +- Sensitive data: activity logs, debug messages, error logs, request values, Team Development files, Session Replay output, and exports avoid unnecessary payload columns, BLOBs, CLOBs, headers, tokens, item values, and secret-bearing URLs. +- Version checks: APEX views and columns were discovered with `APEX_DICTIONARY`, `ALL_OBJECTS`, or `ALL_TAB_COLUMNS` before version-specific SQL was generated. +- Licensed features: AWR, ASH, and Diagnostics Pack usage was called out; non-licensed fallbacks such as live `V$SESSION`, `V$SQL`, ORDS logs, APEX debug, and application instrumentation were considered. +- Security boundaries: APEX session state, hidden items, read-only items, client-side checks, and replay observations were not treated as access control. +- Reproduction safety: journey replay and background-job reruns avoid production side effects such as emails, payments, notifications, approvals, destructive DML, or external calls unless explicitly confirmed. +- Evidence quality: AWR/ASH candidates are treated as correlation evidence, not proof, unless confirmed by SQL ID, ECID, module/action, client identifier, debug page-view ID, or application instrumentation. diff --git a/apex/admin/references/monitoring/user-journey-replay.md b/apex/admin/references/monitoring/user-journey-replay.md new file mode 100644 index 0000000..62e42d8 --- /dev/null +++ b/apex/admin/references/monitoring/user-journey-replay.md @@ -0,0 +1,73 @@ +# End-To-End User Journey Replay + +Use this reference for reproducing critical APEX paths with Session Replay and `APEX_ACTIVITY_LOG`. + +Version check: use `APEX_DICTIONARY` and `ALL_TAB_COLUMNS` before assuming Session Replay, activity-log, debug, or page-view metadata availability. + +## Replay Pre-Check + +Session Replay availability, retention, and exposed metadata vary by APEX release and instance configuration. Use App Builder reports when replay is not exposed through supported SQL views. + +```sql +SELECT view_name, + comments +FROM apex_dictionary +WHERE view_name LIKE '%ACTIVITY%LOG%' + OR view_name LIKE '%DEBUG%MESSAGE%' + OR view_name LIKE '%PAGE%VIEW%' + OR view_name LIKE '%REPLAY%' +ORDER BY view_name; +``` + +```sql +SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name IN ( + 'APEX_ACTIVITY_LOG', + 'APEX_WORKSPACE_ACTIVITY_LOG', + 'APEX_DEBUG_MESSAGES') +ORDER BY table_name, + column_id; +``` + +## Journey Path Reconstruction + +```sql +SELECT view_date, + apex_user, + apex_session_id, + application_id, + application_name, + page_id, + page_name, + page_view_type, + request_value, + elapsed_time, + rows_queried, + debug_page_view_id, + ecid, + CASE WHEN error_message IS NOT NULL THEN 'Y' ELSE 'N' END AS has_error +FROM apex_activity_log +WHERE apex_session_id = :apex_session_id +ORDER BY view_date, + id; +``` + +Compare one failed session with one successful baseline from the same application version and similar data shape. Capture correlation metadata only: APEX session, user, page, request, `DEBUG_PAGE_VIEW_ID`, ECID, timestamp window, and timing/error summary. + +## Replay Safety + +- Do not export Session Replay output unless privacy handling and incident need are confirmed. +- Reproduce destructive, externally visible, payment, email, notification, approval, or workflow actions in non-production first. +- Treat missing steps as evidence: branches, authorization failures, validations, AJAX callbacks, redirects, or expired sessions can remove expected page views. + +## DB Skill Usage + +DB skill in use: `db/performance/ash-analysis.md`, `db/performance/awr-reports.md`, and `db/performance/wait-events.md` for generic ASH/AWR and wait-event interpretation. The APEX monitoring skill is being used for Session Replay, activity-log path, and journey reproduction context. + +After a DB-skill handoff, use the selected DB performance skill's required connection/user, such as a diagnostics/performance account for AWR, ASH, `DBA_HIST`, `V$`, SQL Monitor, or wait-event evidence. Do not reuse the APEX admin connection unless the DB skill explicitly accepts it. + +AWR and ASH require Diagnostics Pack in production. diff --git a/apex/admin/references/monitoring/workspace-monitor-activity.md b/apex/admin/references/monitoring/workspace-monitor-activity.md new file mode 100644 index 0000000..d25e28a --- /dev/null +++ b/apex/admin/references/monitoring/workspace-monitor-activity.md @@ -0,0 +1,107 @@ +# Workspace Monitor Activity + +Use this topic when the user asks about APEX Workspace Administration, Monitor Activity, workspace usage reports, active sessions, developer activity, login attempts, environment, workspace schema reports, web service activity, archived activity, or purged task-file archives. + +Official source: Oracle APEX Administration Guide, "Monitoring Activity within a Workspace": + +```text +https://docs.oracle.com/en/database/oracle/apex/26.1/aeadm/monitoring-activity-within-a-workspace.html#GUID-2DF3D389-30BA-43A9-AD9A-01F583D1B508 +``` + +## Workspace Monitor Reports + +Route these Workspace Administration reports here before choosing deeper SQL, debug, or DB-performance references: + +- Page Views: use for page usage, recent traffic, request timing, and navigation-path triage. Include the documented Page Views report variants: Recent Page Views, By View, By User, By Application, By Weighted Page Performance, By Page Performance, By Application and Page, By Page, By User and Page, and By Page and User. Continue to `activity-log.md` or `page-performance.md` for SQL-backed analysis. +- Developer Activity: use for App Builder and developer-change activity. Cover the documented report variants: Application Changes by Developer, By Day, and By Day and Developer. Treat usernames, timestamps, component names, and application names as sensitive operational metadata. +- Active Sessions: use for currently active APEX sessions, session detail, and temporary investigation of Debug or Trace Mode. Session Detail can show session information, session state, application items, collections, browser request details, session application attributes, workspace, authentication, active debug level, and whether trace is enabled. Do not enable broad production debug or trace without a narrow time window and user confirmation. +- Page View Analysis: use for aggregate request trends and slow-page discovery. Cover the documented report variants: Most Viewed Pages, Application Summary, Monthly Calendar, By Day, By Day and Hour, By User, By Application, By Application and Page, By Page, By User and Page, and By Page and User. Continue to `page-performance.md` or `ir-ig-tuning.md` when the issue is component or report performance. +- Environment: use for workspace/application environment context. Include the Environment report and the About Database report. Do not expose internal URLs, hostnames, schemas, proxy details, or version data unnecessarily. +- Login Attempts: use for authentication triage and suspicious-login review. Treat usernames, IP addresses, and failure messages as sensitive; route generic audit policy or identity-provider investigation to the DB/security or external identity skill. +- Application Errors: use for App Builder error report triage. Continue to `error-handling.md` for APEX error-log and debug correlation. +- Workspace Schema Reports: use for mapped schemas, Schema Tablespace Utilization, Database Privileges, and Workspace Schemas. Keep APEX mapping context here; route generic user creation, grants, quotas, tablespaces, and privilege remediation to the DB skill. +- Web Service Activity Log: use for REST Data Source, Web Source, and outbound web service call activity. Continue to `rest-data-sources.md` for APEX webservice-log analysis. Never print credentials, API keys, bearer tokens, or full secret-bearing URLs. +- Generative AI service utilization, service history, AI token limits, remaining tokens, or token consumption per app: continue to `ai-token-monitoring.md`. Treat prompts, completions, API keys, credential static IDs, and provider details as sensitive. +- Archived Activity: use for historical APEX activity retained by the workspace, including Page Views, By View, By User, By Application, By Weighted Page Performance, By Page Performance, By Application and Page, By Page, By User and Page, and By Page and User. Avoid exporting or pasting bulk logs into chat; summarize counts, time windows, applications, pages, and anonymized patterns. +- Archive of Purged Task Files: use for Team Development task-file archive awareness. Do not retrieve file payloads unless the user explicitly asks and the sensitivity is reviewed. + +## Debug And Trace Controls + +Use Active Sessions when a workspace administrator needs temporary debug or trace inspection for a current session. The documented debug controls include No Debug, Info, App Trace, Full Trace, and APEX Trace. + +Guardrails: + +- Ask for the exact workspace, application, user, session, page, and time window before recommending debug or trace changes. +- Prefer the lowest useful debug level and the shortest practical duration. +- Treat trace output and debug messages as sensitive; they can reveal item values, SQL, component names, URLs, bind values, or error text. +- After the investigation, recommend turning Debug or Trace Mode back off. + +## Identity And Access + +Before MCP-backed monitoring queries, verify the active database identity: + +```sql +SELECT SYS_CONTEXT('USERENV', 'SESSION_USER') AS session_user, + SYS_CONTEXT('USERENV', 'CURRENT_USER') AS current_user, + SYS_CONTEXT('USERENV', 'ISDBA') AS is_dba +FROM dual; +``` + +Continue only when the user confirms the connection is the intended APEX admin identity. If the connection is `SYS`, `ISDBA = TRUE`, an app parsing schema, a workspace developer/end user, an ORDS/APEX runtime account, a generic deployment user, or unknown, stop and ask for the confirmed APEX admin connection. If the connection is `SYSTEM`, continue only after the exact uppercase `YES` confirmation required by `apex/admin/SKILL.md`. This applies to read-only APEX monitoring queries as well as changes. + +If the user asks to enable Debug, Trace Mode, purge activity, change retention, or change APEX schema mappings or users, keep the APEX steps under the confirmed APEX admin identity and load the relevant APEX admin reference before proceeding. For documented instance-level debug API work, use `instance-debug-api.md`. If the request moves to grants, database users, quotas, tablespaces, AWR, ASH, `V$`, `DBA_HIST`, or ORDS runtime diagnostics, stop and route that portion to the DB skill with that skill's required connection/user. + +## Supported View Discovery + +APEX dictionary views and columns vary by release and service. Inspect availability before using SQL-backed report queries: + +```sql +SELECT view_name, + comments +FROM apex_dictionary +WHERE view_name IN ( + 'APEX_WORKSPACE_ACTIVITY_LOG', + 'APEX_ACTIVITY_LOG', + 'APEX_DEBUG_MESSAGES', + 'APEX_WEBSERVICE_LOG', + 'APEX_AUTOMATION_LOG', + 'APEX_AUTOMATION_MSG_LOG') +ORDER BY view_name; +``` + +```sql +SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name IN ( + 'APEX_WORKSPACE_ACTIVITY_LOG', + 'APEX_ACTIVITY_LOG', + 'APEX_DEBUG_MESSAGES', + 'APEX_WEBSERVICE_LOG', + 'APEX_AUTOMATION_LOG', + 'APEX_AUTOMATION_MSG_LOG') +ORDER BY table_name, + column_id; +``` + +## Report-To-Reference Routing + +- Page Views, Active Sessions, Page View Analysis, Archived Activity: `activity-log.md` +- Application Errors, Debug, Trace Mode: `error-handling.md`, `instance-debug-api.md` +- Web Service Activity Log: `rest-data-sources.md` +- Generative AI service utilization, service history, and AI token monitoring: `ai-token-monitoring.md` +- Page or component latency: `page-performance.md`, `ir-ig-tuning.md` +- Workspace schemas and mappings: `../workspace/schema-mapping.md` +- Database privileges, users, quotas, tablespaces, auditing, or identity-provider investigation: announce the DB skill handoff before generating generic DB steps. + +## Security Review + +Before sharing results, check: + +- No passwords, tokens, API keys, authorization headers, or credential values are shown. +- Usernames, IP addresses, URLs, hostnames, schemas, error text, and request values are limited to what the user needs. +- Debug or trace recommendations are scoped to a narrow user, app, page, and time window. +- Bulk logs are summarized instead of pasted. +- Generic DB remediation is routed to the DB skill with a visible handoff message. diff --git a/apex/admin/references/security/audit-columns.md b/apex/admin/references/security/audit-columns.md new file mode 100644 index 0000000..1f0d24c --- /dev/null +++ b/apex/admin/references/security/audit-columns.md @@ -0,0 +1,43 @@ +# APEX Application Table Audit Metadata Review + +Use this reference to review whether APEX application tables appear to have simple change metadata. This is application-level audit metadata, not a replacement for tamper-resistant database auditing. + +DB skill in use: `db/security/auditing.md` for generic database auditing, Unified Auditing, FGA, compliance audit policies, or tamper-resistant audit design. The APEX security skill is being used for APEX-owned application-table audit-column context. + +After this handoff, use the DB auditing skill's required connection/user for audit policies, FGA, Unified Auditing, history tables, Flashback Data Archive, or tamper-resistant audit design. Do not reuse the APEX admin connection unless the DB skill explicitly accepts it. + +## Admin Skill Boundary + +The APEX admin skill must not create, alter, or drop application tables, audit tables, history tables, triggers, packages, constraints, or APEX internal/runtime tables. + +Use this reference only to: + +- inventory whether application-owned tables already expose created/updated metadata; +- check whether existing metadata uses an APEX runtime user context instead of only the parsing schema; +- identify gaps that should be handed off to the owning application, APEXlang, or DB skill; +- record the finding in the local protocol or user-confirmed report. + +Do not generate DDL from this skill. If the user wants audit columns, triggers, history tables, or application instrumentation added, stop and route the implementation to the owning application/APEXlang or DB skill. Any write to an existing customer-owned table is state-changing and requires explicit user confirmation in the owning skill. + +## Review Shape + +When reviewing existing customer-owned application tables, look for consistent metadata such as: + +- created timestamp; +- created user; +- updated timestamp; +- updated user. + +The exact column names and data types are customer/application design choices. Do not impose APEX internal table conventions, `WWV_FLOW_%` conventions, `$` runtime/log table naming, or a specific timestamp datatype from this skill. + +When assessing existing triggers or application logic, prefer APEX runtime context for end-user attribution when available, with a database-user fallback. In APEX runtime, `USER` and `SESSION_USER` commonly identify the parsing schema, not the end user. + +## Guardrails + +- Do not add audit-column triggers, log tables, history tables, or package wrappers from the APEX admin skill. +- Do not create logging tables for skill protocols in an APEX schema, parsing schema, workspace schema, or customer application schema. +- Do not alter existing customer-owned tables from this skill. Writing to existing tables is also state-changing and must be explicitly requested and routed to the owning skill. +- Do not recommend copying passwords, tokens, large payloads, BLOBs, CLOBs, request bodies, item values, or sensitive free text into audit tables by default. +- On hot tables, bulk-load paths, or ETL-heavy workloads, call out row-level trigger cost. +- Consider database-generic alternatives such as compound triggers, history tables, Unified Auditing, or Flashback Data Archive through the relevant DB skill. +- Application change metadata is not a replacement for tamper-resistant database auditing. diff --git a/apex/admin/references/security/guardrails.md b/apex/admin/references/security/guardrails.md new file mode 100644 index 0000000..6db812b --- /dev/null +++ b/apex/admin/references/security/guardrails.md @@ -0,0 +1,58 @@ +# APEX Security Guardrails + +Apply these APEX-specific rules before generating SQL, scripts, or operational steps. + +## Role Boundaries + +Keep APEX role boundaries clear: workspace administrator, developer, end user, parsing schema, database-login user, ORDS/APEX runtime account, and DBA/admin account are different security contexts. + +Run live MCP-backed APEX admin work only under the confirmed APEX admin identity from `apex/admin/SKILL.md`. Do not use `SYS`, `SYSDBA`, parsing schemas, workspace users, ORDS/APEX runtime accounts, generic deployment users, or unknown accounts for routine APEX-owned queries or operations. + +`SYSTEM` without `SYSDBA` is allowed for APEX-admin-scoped work only after the exact uppercase `YES` confirmation defined in `apex/admin/SKILL.md`. The confirmation must show the verified identity, target objects, action scope, password-handling path when relevant, and risk summary. This does not authorize generic DB/ORDS/performance work. + +Do not treat parsing schemas as personal interactive logins in production. If a parsing schema is only technical, keep it narrow and document whether it should be locked outside deployment windows. + +## Least Privilege + +Do not grant broad privileges such as `DBA`, `SYSDBA`, `SELECT ANY TABLE`, `EXECUTE ANY PROCEDURE`, `CREATE ANY TABLE`, `GRANT ANY ROLE`, `GRANT ANY PRIVILEGE`, or `WITH ADMIN OPTION` for ordinary APEX provisioning. + +DB skill in use: `db/security/privilege-management.md` for generic database privilege design. The APEX security skill is being used for APEX workspace, parsing-schema, and runtime-account context. + +After a DB-skill handoff, use that DB security skill's required connection/user. Do not reuse the APEX admin connection for grants, users, quotas, audit policies, encryption, network ACLs, VPD/RLS, masking, or other generic DB security work unless the DB skill explicitly accepts it. + +## Supported Interfaces + +Do not query or write directly to internal APEX repository tables. Use supported public `APEX_*` views and documented APEX APIs as the APEX administration contract. + +Keep APEX admin evidence scoped to the relevant workspace, application, page, session, user, and time window whenever that context is known. If a supported public APEX view is not specific enough for the question, first inspect available supported views and package APIs; do not fall back to internal repository tables. + +Before querying APEX views or package signatures, inspect version-specific availability through `ALL_TAB_COLUMNS`, `ALL_ARGUMENTS`, `APEX_DICTIONARY`, or `APEX_RELEASE`. + +## Session State And Tenant Isolation + +APEX session state, hidden items, read-only items, and client-side checks are not a security boundary. Use server-side authorization, validations, and database privileges. + +For tenant isolation or sensitive row access, describe the APEX authorization context, then use database-enforced isolation. + +DB skill in use: `db/security/row-level-security.md` for VPD/RLS implementation details. The APEX security skill is being used for APEX authorization and UI context. + +When reviewing APEX metadata, call out whether the evidence came from supported public `APEX_*` views, documented APEX APIs, exported application files, or browser/UI evidence. Do not present internal repository state as customer-facing proof. + +## Secrets, Logs, And Exports + +Do not hard-code secrets in APEX examples, exports, logs, scripts, or chat output. This includes database passwords, web credentials, OAuth secrets, SMTP credentials, wallet passwords, and API tokens. + +Treat APEX activity logs, debug logs, error messages, request values, Team Development files, static files, and exports as potentially sensitive. Avoid selecting unnecessary CLOB/BLOB payloads or secret-bearing values during triage. + +Review APEX exports before committing or sharing. They may contain application logic, URLs, authorization schemes, build options, static files, credential references, defaults, and sensitive metadata. + +DB skill in use: `db/security/encryption.md`, `db/security/network-security.md`, or `db/security/data-masking.md` for generic encryption, TLS, network ACL, redaction, and masking implementation. The APEX security skill is being used for APEX-specific exposure and export/log context. + +## Common Mistakes + +- Treating APEX session state, hidden items, read-only items, or client-side checks as a security boundary. +- Querying or updating internal APEX repository tables when supported public `APEX_*` views or documented APEX APIs should be used. +- Leaving live APEX log or metadata queries unscoped when the workspace, application, page, user, session, or time window is known. +- Duplicating generic database security guidance in an APEX skill instead of using `db/security/*`. +- Selecting unnecessary debug, request, Team Development, BLOB, CLOB, or export payloads during operational triage. +- Creating schemas or workspace users with broad privileges because the script runs as an administrator. diff --git a/apex/admin/references/security/safety-messages.md b/apex/admin/references/security/safety-messages.md new file mode 100644 index 0000000..1537221 --- /dev/null +++ b/apex/admin/references/security/safety-messages.md @@ -0,0 +1,73 @@ +# APEX Security Safety Messages + +Use these message patterns when a user request crosses an APEX safety boundary. + +```text +DB skill in use: db/security/privilege-management.md for generic privilege analysis. The APEX skill is being used only for APEX workspace and parsing-schema context. +``` + +```text +APEXlang skill in use: apex/apexlang/SKILL.md for APEX application generation. The APEX admin skill is being used only for workspace, deployment identity, connection safety, and post-deploy validation. +``` + +```text +Connection confirmation: I am connected as SESSION_USER=, CURRENT_USER=, ISDBA=. This APEX admin workflow requires the intended APEX admin identity. Confirm this connection is the APEX admin identity for the target workspace/import before I continue. +``` + +```text +SYSTEM confirmation required: I am connected as SESSION_USER=SYSTEM, CURRENT_USER=SYSTEM, ISDBA=FALSE. SYSTEM is a privileged APEX admin identity for this workflow. Scope: . Targets: . I will not put passwords in chat or logged MCP SQL. Reply exactly YES in uppercase to allow this APEX-admin-scoped work under SYSTEM. +``` + +```text +Protocol file required: this APEX admin workflow includes . I need a local output directory or exact Markdown file path for the operation protocol before I continue. The protocol will stay outside the skill tree and will redact secrets, tokens, request bodies, item values, cookies, and unnecessary personal data. +``` + +```text +DB skill handoff: this evidence or action belongs to . I will use that DB skill's required connection/user for the DB work and keep the APEX admin identity only for APEX workspace, application, page, session, request, and time-window context. +``` + +```text +Safety note: this is generic database security guidance, not APEX-specific behavior. I will route the generic part to db/security/auditing.md and keep the APEX skill focused on the APEX action that needs auditability. +``` + +```text +Safety stop: direct writes to internal APEX repository tables are not supported by this skill. I will use supported APEX APIs or views instead. +``` + +```text +Safety stop: this would grant a broad administrative privilege. Please confirm the exact purpose, target account, and why a narrower privilege is not sufficient before I generate SQL. +``` + +```text +Safety stop: this operation is destructive. I will first list affected workspaces, schemas, APEX users, database users, and related components, then require a fresh exact English confirmation before generating or running delete steps. If database users are included, you must confirm that deleting the listed users/components is your own will. +``` + +```text +Recovery check: this APEX provisioning workflow was interrupted. I will inventory the planned workspace, schema mappings, APEX users, database users, application tables, and APEX applications one by one, then ask whether you want to roll back only the listed artifacts. +``` + +```text +Sensitive data warning: APEX logs, debug output, request values, Team Development files, and exports may contain secrets or personal data. I will avoid selecting payload columns unless you explicitly need them. +``` + +```text +Security warning: APEX session state, hidden items, read-only items, and client-side checks are not security boundaries. I will use server-side authorization, validations, and database privileges for enforcement. +``` + +```text +Audit note: the trigger pattern records application change metadata only. It is not a replacement for tamper-resistant database auditing; use db/security/auditing.md for that. +``` + +```text +Version check: this APEX view or package signature can vary by release. I will inspect available columns or arguments before generating version-specific SQL. +``` + +```text +Unsupported APEX version detected: . The APEX admin skill supports only currently supported APEX releases: 26.1, 24.2, and 24.1 as of June 2026. I will stop before generating APEX admin SQL or change steps for this environment. +``` + +```text +APEX MCP availability check failed: the MCP transport is closed, so I cannot safely verify or change APEX state from here. I will pause the APEX workflow until the MCP tool channel is available again. +``` + +Emit these messages before continuing when the request involves APEX application generation handoff, MCP-backed application create/import connection confirmation, required local protocol output, DB-skill handoff, unsupported APEX versions, broad grants, direct internal repository writes, destructive changes, interrupted provisioning recovery, sensitive logs/exports, session-state security assumptions, audit triggers, version-sensitive APEX views, or unavailable MCP-backed database access. diff --git a/apex/admin/references/security/security-review.md b/apex/admin/references/security/security-review.md new file mode 100644 index 0000000..9cd4600 --- /dev/null +++ b/apex/admin/references/security/security-review.md @@ -0,0 +1,18 @@ +# APEX Security Review + +Use this checklist after substantial APEX workspace or application-support changes. + +- APEX admin identity: every live MCP-backed APEX admin step used the confirmed APEX admin identity, not `SYS`, `SYSDBA`, a parsing schema, workspace user, ORDS/APEX runtime account, generic deployment user, or unknown account. If `SYSTEM` was used, the exact uppercase `YES` confirmation, scope, targets, and risk summary were recorded before work continued. +- Protocol file: every substantive live APEX admin workflow, state-changing workflow, customer-evidence analysis, and debugging workflow created or updated a local protocol file outside the skill tree. +- DB handoff identity: every generic DB/security step used the selected DB skill's required connection/user rather than silently reusing the APEX admin connection. +- Privileges: parsing schemas, workspace users, database-login users, and automation accounts have only the required rights. +- Role boundaries: workspace administrator, developer, end user, parsing schema, runtime account, and DBA/admin roles are not mixed. +- Secrets: no real passwords, web credentials, OAuth secrets, SMTP credentials, wallet passwords, or API tokens appear in scripts, exports, logs, examples, or chat output. +- Data exposure: activity logs, debug logs, request values, Team Development files, static files, exports, and audit columns do not expose unnecessary sensitive data. +- Auditability: workspace creation/removal, user creation, schema mapping changes, imports/exports, grants, role changes, and credential changes are traceable. +- Supported interfaces: evidence and automation used supported public `APEX_*` views and documented APEX APIs; no internal APEX repository tables were queried or updated as shortcuts. +- Scope: live queries and evidence collection were limited to the known workspace, application, page, session, user, and time window where available. +- Version and cloud limits: APEX package signatures, APEX view columns, Autonomous Database limits, and managed-service restrictions are checked before use. +- Destructive actions: affected objects are listed, protected accounts are blocked, and explicit confirmations are required. +- DB skill usage: generic security, performance, ORDS, SQLcl, masking, encryption, VPD/RLS, or auditing work is routed to the relevant `db/...` skill and announced with a visible `DB skill in use:` message. +- Output: final security-sensitive answers include a compact summary of checks performed, checks not performed because evidence or permissions were unavailable, and handoffs made to DB/ORDS/APEXlang. diff --git a/apex/admin/references/workspace/instance-admin-api.md b/apex/admin/references/workspace/instance-admin-api.md new file mode 100644 index 0000000..e5718db --- /dev/null +++ b/apex/admin/references/workspace/instance-admin-api.md @@ -0,0 +1,114 @@ +# APEX Instance Admin API + +Use this reference when an APEX administration workflow should prefer the documented `APEX_INSTANCE_ADMIN` package instead of internal APEX repository tables or ad hoc SQL. + +Official source: Oracle APEX 26.1 API Reference, `APEX_INSTANCE_ADMIN`: + +```text +https://docs.oracle.com/en/database/oracle/apex/26.1/aeapi/APEX_INSTANCE_ADMIN.html +``` + +The package manages APEX runtime-environment settings and schema-to-workspace mappings. Oracle documents that it can be executed by `SYS`, `SYSTEM`, and database users granted `APEX_ADMINISTRATOR_ROLE`; this skill still applies the APEX Admin Identity Gate from `apex/admin/SKILL.md` and does not use `SYS` or `SYSDBA` for routine MCP-backed APEX admin work. + +## Default Rule + +Prefer documented `APEX_INSTANCE_ADMIN` APIs for APEX instance administration tasks that are in scope for this skill. Do not query or update internal APEX repository tables directly. + +Before generating executable calls: + +1. Verify the installed APEX version and supported-version gate. +2. Verify the active identity with the APEX Admin Identity Gate. +3. Resolve the installed package or synonym and inspect `ALL_ARGUMENTS` before relying on version-sensitive parameters. +4. Load the specific workflow reference for lifecycle, schema mapping, removal, resource governance, or deployment identity. +5. For state-changing calls, create or update the local protocol file and require explicit user confirmation of the exact target and scope. + +## Package Signature Check + +`APEX_INSTANCE_ADMIN` may be a synonym for the real APEX package. Resolve it before checking procedure arguments: + +```sql +WITH apex_instance_admin_target AS ( + SELECT owner, + object_name AS package_name + FROM all_objects + WHERE object_name = 'APEX_INSTANCE_ADMIN' + AND object_type = 'PACKAGE' + UNION ALL + SELECT table_owner AS owner, + table_name AS package_name + FROM all_synonyms + WHERE synonym_name = 'APEX_INSTANCE_ADMIN' +) +SELECT DISTINCT + a.owner, + a.package_name, + a.object_name, + a.overload, + a.sequence, + a.position, + a.argument_name, + a.in_out, + a.data_type, + a.defaulted +FROM apex_instance_admin_target t +JOIN all_arguments a + ON a.owner = t.owner + AND a.package_name = t.package_name +WHERE a.object_name = UPPER(:procedure_name) +ORDER BY a.owner, + a.package_name, + a.overload, + a.sequence; +``` + +## Owned APEX Admin APIs + +These APIs are in scope when the matching workflow reference is loaded and the identity/confirmation gates pass: + +- `ADD_WORKSPACE`: create APEX workspaces. Use `lifecycle.md`. +- `REMOVE_WORKSPACE`: remove APEX workspaces. Use `removal.md`. +- `ADD_SCHEMA`: map schemas to workspaces. Use `schema-mapping.md`; pass `p_grant_apex_privileges => TRUE` when supported and standard APEX grants are required. +- `REMOVE_SCHEMA`: remove schema mappings from workspaces. Use `schema-mapping.md` or `removal.md`. +- `GET_SCHEMAS`: inspect workspace schema mappings. Use `schema-mapping.md`. +- `GET_PARAMETER`: inspect APEX instance parameters. Use `lifecycle.md` or `resource-governance.md`. +- `SET_PARAMETER`: change APEX instance parameters only after explicit confirmation and protocol logging. Use the specific reference for the setting. +- `GET_WORKSPACE_PARAMETER`: inspect workspace-level APEX parameters. Use `resource-governance.md`. +- `SET_WORKSPACE_PARAMETER`: change workspace-level APEX parameters only after explicit confirmation and protocol logging. Use `resource-governance.md`. +- `CREATE_OR_UPDATE_ADMIN_USER`: use only when the request is explicitly for a documented APEX administration user path and the environment policy accepts this API. Do not use it for initial `INTERNAL` Instance Administrator bootstrap; use `../deployment/instance-admin-bootstrap.md`. +- `UNLOCK_USER`: use only for APEX-managed admin/user unlock workflows after confirming the target user and workspace or instance context. Use `users-and-auth.md`. + +## Allowed With Extra Care + +These APIs can affect broad instance behavior, security posture, logs, or external integrations. Use only with a narrow scope, exact confirmation, and protocol logging: + +- `ADD_AUTO_PROV_RESTRICTIONS`, `REMOVE_AUTO_PROV_RESTRICTIONS`: workspace provisioning governance. +- `CREATE_SCHEMA_EXCEPTION`, `REMOVE_SCHEMA_EXCEPTION`, `REMOVE_SCHEMA_EXCEPTIONS`: schema restriction exceptions. +- `RESTRICT_SCHEMA`, `UNRESTRICT_SCHEMA`: instance-level schema availability. +- `ADD_WEB_ENTRY_POINT`, `REMOVE_WEB_ENTRY_POINT`: external entry-point behavior. +- `SET_LOG_SWITCH_INTERVAL`, `TRUNCATE_LOG`: log retention or volume controls. +- `SET_WORKSPACE_CONSUMER_GROUP`: workspace resource governance. +- `RESERVE_WORKSPACE_APP_IDS`, `FREE_WORKSPACE_APP_IDS`: workspace application ID reservation. +- `REMOVE_APPLICATION`: destructive application removal; require export/backup confirmation and route to deployment/removal checks. +- `REMOVE_SAVED_REPORT`, `REMOVE_SAVED_REPORTS`, `REMOVE_SUBSCRIPTION`: user/application metadata cleanup. + +## Route Or Avoid By Default + +Do not treat every documented API as a default admin automation target: + +- `CREATE_CLOUD_CREDENTIAL` and `DROP_CLOUD_CREDENTIAL`: route credential handling to the appropriate secure credential/DB/cloud workflow. Never collect credential secrets in chat or skill files. +- `DB_SIGNATURE` and `IS_DB_SIGNATURE_VALID`: use only when troubleshooting APEX runtime integrity with an explicit Oracle-supported reason; do not use as a general health check. +- `GRANT_EXTENSION_WORKSPACE` and `REVOKE_EXTENSION_WORKSPACE`: use only when the user explicitly asks for extension-workspace governance and the environment supports it. +- `VALIDATE_EMAIL_CONFIG`: allowed for APEX email configuration validation, but do not expose SMTP credentials or secret configuration values. + +If an `APEX_INSTANCE_ADMIN` API overlaps with generic database users, grants, quotas, tablespaces, ORDS, AWR/ASH, SQL Monitor, or infrastructure diagnostics, stop and route that portion to the DB/ORDS skill. + +## Security Review + +Before sharing results or runnable steps, verify: + +- The selected API is documented for the installed APEX version. +- The active identity is a confirmed APEX admin identity or the explicit `SYSTEM` exception has passed. +- `SYS` and `SYSDBA` are not used for routine MCP-backed APEX admin work. +- State-changing calls have an exact target list, confirmation, protocol file, and rollback/cleanup note where applicable. +- Customer names, workspace names, schema names, users, URLs, and settings are redacted or minimized in chat. +- Generic DB, ORDS, AWR/ASH, SQL Monitor, grants, quotas, tablespaces, and schema creation were handed off instead of being absorbed into this skill. diff --git a/apex/admin/references/workspace/lifecycle.md b/apex/admin/references/workspace/lifecycle.md new file mode 100644 index 0000000..fb4eea6 --- /dev/null +++ b/apex/admin/references/workspace/lifecycle.md @@ -0,0 +1,278 @@ +# APEX Workspace Lifecycle + +Use this topic for workspace inventory, pre-flight checks, create workspace, and verification. + +For documented `APEX_INSTANCE_ADMIN` API ownership, signature checks, and sensitive API classification, use `instance-admin-api.md` before generating executable package calls. + +## Pre-Flight Questions + +- APEX version, because package signatures differ across APEX releases. +- Run the supported-version gate in `references/workspace/version-notes.md`. If the installed APEX version is unsupported, stop before workspace inventory, create, schema mapping, user changes, or application handoff. +- Check the instance feature-configuration parameter `WORKSPACE_PROVISION_DEMO_OBJECTS` before workspace creation and confirm whether demonstration applications/database objects should be created. For clean customer, production, CI, or migration workspaces, recommend `N` unless the user explicitly asks for demo/training objects. +- Target workspace name and whether a deterministic workspace ID is required. +- Workspace description or administrative notes that should be recorded during provisioning. +- Primary parsing schema and any additional schemas. +- Always ask whether the workspace should use a new database user/schema or an existing database user/schema before creating the workspace. Do not infer this from the requested workspace name. +- If a new database user/schema is requested, route generic user creation, password handling, tablespace, quota, and manual grants through the relevant DB skills before APEX workspace mapping. After the database user/schema exists, apply APEX-managed standard schema privileges through `APEX_INSTANCE_ADMIN.ADD_SCHEMA(..., p_grant_apex_privileges => TRUE)` when the installed APEX version supports that parameter and the schema is not already mapped. +- If an existing database user/schema is requested, verify it with `references/workspace/schema-mapping.md` before workspace creation. +- For schema-to-workspace mappings where `APEX_INSTANCE_ADMIN.ADD_SCHEMA` supports `p_grant_apex_privileges`, use `p_grant_apex_privileges => TRUE` as the standard APEX-managed grant behavior unless the user or environment policy explicitly opts out. This applies the standard privileges from `APEX_GRANTS_FOR_NEW_USERS_ROLE`. Manual `GRANT`/`REVOKE` remediation remains a DB-skill handoff. +- Whether the first user should be an APEX workspace administrator, developer, or end user. +- For bulk provisioning, ask for the workspace naming method, workspace count, quota, Resource Manager consumer group, automatic-purge setting, demo-object policy, email-address input when relevant, and confirmation policy before any create loop. +- Authentication model for the development environment. +- Confirm parsing-schema candidates with `references/workspace/schema-mapping.md`; do not suggest ORDS schemas, `PDB_ADMIN`, Oracle-maintained accounts, APEX platform schemas, or DBA/runtime service accounts as parsing schemas. +- If the user wants to reuse an existing parsing schema, verify required privileges first. If privileges are missing or excessive, ask whether the user wants the DB privilege changes handled through `db/security/privilege-management.md`; continue only when the privileges are correct or the user approves adjustment. +- Whether this is Oracle Cloud or Autonomous Database, where some instance administration options may be restricted. +- If a dedicated APEX admin database account with `APEX_ADMINISTRATOR_ROLE` is unavailable, cannot be verified, or the role setup appears incomplete, stop before workspace creation. Ask whether the user wants to use `SYSTEM` without `SYSDBA` once to create/repair the dedicated APEX admin account setup, or continue the APEX-admin-scoped workflow as `SYSTEM`. Either path requires `SESSION_USER = SYSTEM`, `CURRENT_USER = SYSTEM`, `ISDBA = FALSE`, a visible scope/risk/password-handling summary, and a fresh exact uppercase `YES`. + +## Administration Services Operation Coverage + +Use this section to map Oracle APEX 26.1 Administration Services workspace-creation operations to this skill. Keep APEX administration here and route generic database administration to the selected DB skill. + +Provisioning method settings: + +- Manual: Instance administrators create workspaces and notify workspace administrators. Use this skill for the APEX workspace decision and verification steps. +- Request: users request workspaces, administrators approve requests, email verification creates the workspace, and status moves from accepted to approved. Before advising this path, confirm APEX email configuration and notification-address requirements. +- Automatic: similar to Request, but requests are approved without administrator review. Call out the governance risk and any disabled-provisioning message requirement before recommending it. +- Oracle Cloud or managed-service restrictions may remove or alter these Administration Services options. Ask for the environment type and route service-specific administration to the cloud/service path when local instance settings are unavailable. + +Manual Create Workspace Wizard coverage: + +- Identify Workspace: collect unique workspace name, optional positive workspace ID greater than 100000 when deterministic ID is required, and description. +- Identify Schema, existing schema: select an existing application-owned schema, inspect suggested additional privileges, and use `references/workspace/schema-mapping.md` before mapping it. When supported, use APEX-managed grants through `p_grant_apex_privileges => TRUE`; route manual grants or privilege remediation to `db/security/privilege-management.md`. +- Identify Schema, new schema: collect intended schema name and quota, but route database-user creation, password handling, tablespace, datafile, quota, and manual grants to the DB skill before the APEX workspace API step. After the database user/schema exists, use APEX-managed grants with `p_grant_apex_privileges => TRUE` for supported schema mappings. +- Identify Administrator: use `references/workspace/users-and-auth.md` for the initial workspace administrator and password-handling guardrails. +- Confirm selections: summarize workspace name, workspace ID policy, schema model, additional schemas, quota/storage implications, initial administrator, environment type, and DB-skill handoffs before creating. + +Feature Configuration side effects: + +- The Administration Services setting `Create demonstration objects in new workspaces` maps to `APEX_INSTANCE_ADMIN` parameter `WORKSPACE_PROVISION_DEMO_OBJECTS`. In APEX 26.1, `Y` creates demonstration applications and database objects in new workspaces; `N` prevents that side effect. +- Treat this as an instance-level setting, not as a per-workspace option. Before workspace creation, show the current value and ask for the desired policy. +- If the current value conflicts with the user's desired policy, stop before creating the workspace. Ask whether the user wants to change the instance setting, change it in the Administration Services UI, or proceed with the documented side effect. Do not call `APEX_INSTANCE_ADMIN.SET_PARAMETER` without explicit confirmation. +- If the setting is changed only for one provisioning run, record the previous value and ask whether to restore it after workspace verification. + +Runtime-environment SQLcl path: + +- Oracle's runtime-environment documentation shows `SYS AS SYSDBA`, `ALTER SESSION SET CURRENT_SCHEMA = APEX_`, and `APEX_INSTANCE_ADMIN.ADD_WORKSPACE`. +- Do not run this path as a routine MCP APEX admin operation. MCP-backed workspace creation in this skill uses the confirmed APEX admin identity from `apex/admin/SKILL.md`. +- If the user explicitly needs the documented `SYS AS SYSDBA` runtime-installation path, classify it as privileged DB/admin work, ask before switching to the relevant DB skill, and use that DB skill's required connection/user. This skill may still provide APEX workspace parameters and post-create verification. + +Creating multiple workspaces: + +- Cover the three Administration Services naming modes: system-generated workspace names, static prefix with sequential integer suffix, and email-domain workspace names with suffixes for duplicates. +- Collect all wizard inputs before generating a plan: workspace count or email-address source, demo-object policy, space quota, Resource Manager consumer group, automatic-purge eligibility, and description. +- Treat bulk creation as destructive-enough to require a preview and explicit confirmation of the exact naming pattern, count, schema model, quota, and administrator/contact policy. +- Do not use internal APEX repository tables for bulk creation. Use supported APEX APIs only when signatures are verified for the installed version, or instruct the user to use the Administration Services wizard when no supported API shape is available. + +Oracle-Managed Files and storage: + +- When creating a workspace with a new schema, a new tablespace and data file may be created for that schema. If Oracle-Managed Files is enabled, data-file placement follows `DB_CREATE_FILE_DEST`; otherwise placement follows the database's tablespace/data-file conventions. +- Keep this as a storage-governance input in the APEX plan. Route `DB_CREATE_FILE_DEST`, datafile placement, tablespace creation, and filesystem/storage remediation to the DB skill with its required connection/user. + +## List Workspaces + +Use `APEX_WORKSPACES` for workspace inventory. + +```sql +SELECT workspace_id, + workspace, + workspace_display_name, + path_prefix, + schemas, + applications, + apex_developers, + apex_workspace_administrators, + allow_app_building_yn, + allow_sql_workshop_yn, + allow_restful_services_yn, + created_on +FROM apex_workspaces +ORDER BY workspace; +``` + +If you need a version-safe query, inspect installed columns first: + +```sql +SELECT column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name = 'APEX_WORKSPACES' +ORDER BY column_id; +``` + +## Create A Workspace + +Run instance-level workspace APIs with a dedicated non-SYS/SYSTEM database account granted `APEX_ADMINISTRATOR_ROLE` when available. If the user intentionally chooses `SYSTEM`, allow it only under the exact uppercase `YES` confirmation gate in `apex/admin/SKILL.md`. Do not connect MCP or routine automation as `SYS` or `SYSDBA` for workspace creation. + +Use `SYS` only for explicit APEX installation, upgrade, emergency DBA, or grant-management work. Treat those as privileged database administration tasks and route them to the appropriate database/admin skill. Do not grant broad DBA privileges just to automate workspace creation. + +`SYSTEM` may be used inside this skill for APEX-admin-scoped work, including workspace creation, workspace-user administration, supported APEX API automation, and creating or granting a dedicated APEX admin account. It is allowed only when `SESSION_USER = SYSTEM`, `CURRENT_USER = SYSTEM`, `ISDBA = FALSE`, the exact target objects, action, password-handling path when relevant, and risk summary are shown, and the user replies with exactly `YES` in uppercase. Do not put passwords in chat, scripts, SQL text, or logged MCP tool calls. + +If the workspace run needs a dedicated APEX admin database account first, ask the user which path they choose: + +```text +No verified APEX admin account with APEX_ADMINISTRATOR_ROLE is available. + +Choose one: +1. Use SYSTEM without SYSDBA once to create or repair the APEX admin account. +2. Continue this APEX-admin-scoped task as SYSTEM. + +I will verify SESSION_USER, CURRENT_USER, and ISDBA first. Passwords will not be logged. Continue only after the scope is shown and you reply exactly YES. +``` + +For password handling, do not ask the user to paste a password into chat. Prefer an interactive local SQLcl prompt or a placeholder-backed local secret. If the user wants a generated strong password, provide a local generator command for the user to run themselves and tell them to enter the result only at the password prompt; do not print generated secrets through chat or MCP/tool output. + +Before creating a workspace through MCP-backed automation, run the identity guard: + +```sql +SELECT SYS_CONTEXT('USERENV', 'SESSION_USER') AS session_user, + SYS_CONTEXT('USERENV', 'CURRENT_USER') AS current_user, + SYS_CONTEXT('USERENV', 'ISDBA') AS is_dba +FROM dual; +``` + +If `SESSION_USER` or `CURRENT_USER` is `SYS`, or `IS_DBA` is `TRUE`, stop. Ask for a confirmed APEX admin connection. If the identity is `SYSTEM`, continue only after the exact uppercase `YES` confirmation required by `apex/admin/SKILL.md`. + +Then check the demo-object provisioning setting: + +```sql +SELECT APEX_INSTANCE_ADMIN.GET_PARAMETER('WORKSPACE_PROVISION_DEMO_OBJECTS') AS workspace_provision_demo_objects +FROM dual; +``` + +For clean customer, production, CI, or migration workspaces, stop if the value is `Y` unless the user explicitly confirms that demonstration applications and database objects are desired for this workspace creation. + +Only after explicit confirmation to change the instance setting: + +```sql +BEGIN + APEX_INSTANCE_ADMIN.SET_PARAMETER( + p_parameter => 'WORKSPACE_PROVISION_DEMO_OBJECTS', + p_value => :demo_objects_yn); +END; +/ +``` + +```sql +BEGIN + APEX_INSTANCE_ADMIN.ADD_WORKSPACE( + p_workspace_id => :workspace_id, + p_workspace => :workspace_name, + p_primary_schema => :primary_schema); +END; +/ +``` + +Check `APEX_INSTANCE_ADMIN.ADD_WORKSPACE` arguments with `ALL_ARGUMENTS` before using version-specific parameters. Do not add `p_grant_apex_privileges` to `ADD_WORKSPACE` unless the installed package signature explicitly exposes it. In current APEX 26.1 package shapes, the APEX-managed grant switch is on `ADD_SCHEMA`, not necessarily on `ADD_WORKSPACE`. + +For additional schema mappings, or when the schema is not already mapped by `ADD_WORKSPACE`, use the APEX-managed grant standard from `references/workspace/schema-mapping.md`: + +```sql +BEGIN + APEX_INSTANCE_ADMIN.ADD_SCHEMA( + p_workspace => :workspace_name, + p_schema => :schema_name, + p_grant_apex_privileges => TRUE); +END; +/ +``` + +## Verify + +After creation, verify workspace, schema mappings, APEX users, and expected privileges through supported APEX views. If the schema was mapped with `p_grant_apex_privileges => TRUE`, record that APEX-managed standard grants were requested. If a primary schema was mapped through `ADD_WORKSPACE` and the installed `ADD_WORKSPACE` signature does not expose `p_grant_apex_privileges`, verify the privileges explicitly. If expected privileges are still missing, route remediation to `db/security/privilege-management.md`; do not generate manual grants from this skill. Do not query or update internal APEX repository tables directly. + +## Application Creation Boundary + +Workspace creation and APEX application creation are separate skill boundaries. If the user wants to create a starter application after workspace provisioning, first verify the workspace and schema mapping, then announce the handoff: + +```text +APEXlang skill in use: apex/apexlang/SKILL.md for APEX application generation. The APEX admin skill is being used only for workspace, deployment identity, connection safety, and post-deploy validation. +``` + +Load `apex/apexlang/SKILL.md` for the actual application scaffold or APEXlang artifacts. Keep this workspace lifecycle topic only for workspace inventory, schema mapping, APEX user setup, and post-create verification. + +Before MCP-backed application materialization, validation, or import continues, show the verified connection identity and continue only after the user confirms it is the intended APEX admin identity. Do not reuse the workspace-provisioning connection silently, and do not switch to a generic deployment user inside this APEX admin skill. + +## Provisioning Recovery After Interruption + +If a workspace provisioning workflow is interrupted, aborted, or loses MCP/database connectivity after any create step may have run, do not continue or retry blindly. Reconnect first, then inventory each planned artifact individually before deciding what to do next. + +Check only the objects that were part of the current provisioning plan: + +```sql +SELECT workspace_id, + workspace, + schemas, + applications, + apex_developers, + apex_workspace_administrators +FROM apex_workspaces +WHERE workspace = UPPER(TRIM(:workspace_name)); +``` + +```sql +SELECT workspace_name, + schema +FROM apex_workspace_schemas +WHERE workspace_name = UPPER(TRIM(:workspace_name)) +ORDER BY schema; +``` + +```sql +SELECT workspace_name, + user_name, + email, + is_admin, + is_application_developer, + account_locked +FROM apex_workspace_apex_users +WHERE workspace_name = UPPER(TRIM(:workspace_name)) +ORDER BY user_name; +``` + +```sql +SELECT username, + account_status, + oracle_maintained +FROM dba_users +WHERE username IN ( + UPPER(TRIM(:primary_schema)), + UPPER(TRIM(:database_login_user)) +) +ORDER BY username; +``` + +```sql +SELECT owner, + object_name, + object_type, + status +FROM all_objects +WHERE owner = UPPER(TRIM(:primary_schema)) + AND object_name IN ('EMP') +ORDER BY object_type, object_name; +``` + +```sql +SELECT workspace, + application_id, + application_name, + alias +FROM apex_applications +WHERE workspace = UPPER(TRIM(:workspace_name)) +ORDER BY application_id; +``` + +Report the recovered inventory in concrete terms: created, missing, or unknown for each planned workspace, schema mapping, APEX user, database user, application table, and APEX application. + +Then ask before cleanup: + +```text +I found the following artifacts from the interrupted APEX provisioning workflow: . Do you want me to roll back the listed artifacts by removing only these objects? +``` + +If the user wants cleanup, route the destructive part through `references/workspace/removal.md` and require its exact English confirmation for the current cleanup scope. If the user wants to continue instead, proceed only from the freshly verified inventory and skip create steps for objects that already exist. + +DB skill in use: `db/security/privilege-management.md` for generic schema/user privilege design. The APEX workspace skill is being used for workspace and parsing-schema context. + +After this handoff, use the selected DB skill's required connection/user for user creation, grants, quotas, tablespaces, and privilege remediation. Do not reuse the APEX admin connection unless the DB skill explicitly accepts it. diff --git a/apex/admin/references/workspace/removal.md b/apex/admin/references/workspace/removal.md new file mode 100644 index 0000000..072dce6 --- /dev/null +++ b/apex/admin/references/workspace/removal.md @@ -0,0 +1,97 @@ +# APEX Workspace Removal + +Use this topic for guarded test-workspace removal and cleanup. Treat removal as destructive. + +Version check: use `ALL_TAB_COLUMNS` and `ALL_ARGUMENTS` before assuming workspace inventory columns or `APEX_INSTANCE_ADMIN.REMOVE_WORKSPACE` parameters. + +MCP-backed workspace inventory and removal must use the confirmed APEX admin identity from `apex/admin/SKILL.md`. Do not remove or inventory APEX workspace objects under `SYS`, `SYSDBA`, parsing schemas, workspace users, ORDS/APEX runtime accounts, generic deployment users, or unknown accounts. `SYSTEM` is allowed only after the exact uppercase `YES` confirmation required by the APEX Admin Identity Gate. + +## Safety Rules + +Safety stop: list affected workspaces, schemas, APEX users, database users, and tablespaces, then require explicit English confirmation before generating or running delete steps. + +Do not use stale context to infer the target. Require the workspace name and a fresh exact English confirmation for the current request. + +Protected accounts must never be deleted: Oracle-maintained users, APEX platform users, ORDS users, runtime accounts, DBA/admin accounts, and shared service accounts. + +## Confirmation Contract + +Before removing a workspace or any workspace-related database user, show the affected-object inventory and require the user to reply with the exact English confirmation phrase in the current conversation. Do not accept `yes`, `y`, screenshots, previous confirmations, branch names, or implied approval. + +For workspace metadata removal only, use this prompt: + +```text +To remove workspace , reply with exactly: YES, I confirm that I want to delete this workspace and that this is my own will. This will remove the listed APEX workspace metadata. Database users and tablespaces will not be dropped by this APEX workflow. +``` + +For workspace removal with related database users/components, use this prompt: + +```text +To remove workspace and the listed related database users/components, reply with exactly: YES, I confirm that I want to delete this workspace and its listed related database users/components and that this is my own will. +``` + +## Affected Object Inventory + +```sql +SELECT workspace_id, + workspace, + workspace_display_name, + schemas, + applications, + apex_developers, + apex_workspace_administrators +FROM apex_workspaces +WHERE workspace = UPPER(TRIM(:workspace_name)); +``` + +```sql +SELECT workspace_name, + schema +FROM apex_workspace_schemas +WHERE workspace_name = UPPER(TRIM(:workspace_name)) +ORDER BY schema; +``` + +```sql +SELECT workspace_name, + user_name, + is_admin, + is_application_developer +FROM apex_workspace_apex_users +WHERE workspace_name = UPPER(TRIM(:workspace_name)) +ORDER BY user_name; +``` + +## Removal Guardrail + +Use `APEX_INSTANCE_ADMIN.REMOVE_WORKSPACE` only after the exact English confirmation for the current removal scope. + +Default to workspace metadata removal only. Keep `p_drop_users => 'N'` and `p_drop_tablespaces => 'N'` unless the user explicitly asks to delete the workspace and the listed related database users/components. + +```sql +BEGIN + APEX_INSTANCE_ADMIN.REMOVE_WORKSPACE( + p_workspace => :workspace_name, + p_drop_users => 'N', + p_drop_tablespaces => 'N'); +END; +/ +``` + +If the user explicitly asks to delete the workspace and the listed related database users/components, and only after the exact English confirmation phrase for that broader scope, `p_drop_users => 'Y'` is allowed. + +```sql +BEGIN + APEX_INSTANCE_ADMIN.REMOVE_WORKSPACE( + p_workspace => :workspace_name, + p_drop_users => 'Y', + p_drop_tablespaces => 'N'); +END; +/ +``` + +Keep `p_drop_tablespaces => 'N'` unless the user explicitly lists tablespace deletion in the requested scope and confirms that scope with the same English own-will confirmation pattern. + +DB skill in use: `db/agent/destructive-op-guards.md` for generic destructive-operation safety patterns. The APEX workspace skill is being used for APEX workspace object inventory and supported removal API context. + +If cleanup crosses into generic database users, grants, quotas, tablespaces, or other non-APEX objects, route that portion to the relevant DB skill and use that skill's required connection/user. Do not reuse the APEX admin connection for DB-skill cleanup unless the DB skill explicitly accepts it. diff --git a/apex/admin/references/workspace/resource-governance.md b/apex/admin/references/workspace/resource-governance.md new file mode 100644 index 0000000..e39988b --- /dev/null +++ b/apex/admin/references/workspace/resource-governance.md @@ -0,0 +1,52 @@ +# APEX Workspace Resource Governance + +Use this workflow when reviewing workspace limits, storage pressure, request ceilings, active session counts, or whether a workspace quota should be adjusted. Keep this topic focused on APEX workspace limits and governance context. For Generative AI token limits, remaining tokens, AI service utilization, or token consumption per application, route to `../monitoring/ai-token-monitoring.md`. + +DB skill in use: `db/performance/ash-analysis.md`, `db/performance/awr-reports.md`, `db/performance/wait-events.md`, and `db/monitoring/space-management.md` for generic CPU, I/O, wait-event, AWR/ASH, and tablespace analysis. The APEX workspace skill is being used for workspace quota, schema mapping, file-storage, and Resource Manager context. + +After a DB-skill handoff, use the selected DB skill's required connection/user, such as a diagnostics/performance account for AWR, ASH, `DBA_HIST`, `V$`, and wait-event evidence or a storage/DB administration identity for tablespace analysis. Do not reuse the APEX admin connection unless the DB skill explicitly accepts it. + +## Quota Source Pre-Check + +Workspace quota and resource metadata varies by APEX release and managed environment. Check available public APEX views and columns first; do not assume a dedicated quota view exists. + +Version check: use `APEX_DICTIONARY` and `ALL_TAB_COLUMNS` before assuming workspace quota, schema, or Resource Manager metadata columns. + +```sql +SELECT view_name, + comments +FROM apex_dictionary +WHERE view_name IN ( + 'APEX_WORKSPACES', + 'APEX_WORKSPACE_SCHEMAS') + OR view_name LIKE '%QUOTA%' + OR view_name LIKE '%RESOURCE%' +ORDER BY view_name; +``` + +```sql +SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name IN ( + 'APEX_WORKSPACES', + 'APEX_WORKSPACE_SCHEMAS') +ORDER BY table_name, + column_id; +``` + +## APEX Governance Checks + +Use `APEX_WORKSPACES`, `APEX_WORKSPACE_SCHEMAS`, and any discovered supported quota or resource views to review file storage, session/request ceilings, application counts, and Resource Manager mapping. Columns such as `FILE_STORAGE_MAX` and `RM_CONSUMER_GROUP` are version-dependent; inspect columns first. + +Generative AI token limits are separate governance signals. Use `../monitoring/ai-token-monitoring.md` for AI service, workspace, provider, and app-level token questions instead of treating AI tokens as storage, session, or Resource Manager quota. + +Do not treat database CPU/I/O pressure as a quota problem without mapped-schema and time-window evidence. Use APEX workspace/application/page context to choose a time window, then use the DB skills for generic resource analysis. + +## Recommendations + +- Adjust APEX workspace quotas only after identifying whether pressure comes from APEX file storage, parsing-schema segment growth, sessions, requests, or database CPU/I/O. +- Do not increase quotas to hide application design issues such as large file uploads, excessive debug logging, or inefficient report downloads. +- Mark AWR/ASH/Diagnostics Pack constraints before using historical DB performance views. diff --git a/apex/admin/references/workspace/schema-mapping.md b/apex/admin/references/workspace/schema-mapping.md new file mode 100644 index 0000000..766f97d --- /dev/null +++ b/apex/admin/references/workspace/schema-mapping.md @@ -0,0 +1,222 @@ +# APEX Workspace Schema Mapping + +Use this topic for parsing schema mappings, additional schemas, workspace export/import preparation, and deployment handoff. + +MCP-backed APEX schema-mapping reads and `APEX_INSTANCE_ADMIN.ADD_SCHEMA` calls must use the confirmed APEX admin identity from `apex/admin/SKILL.md`. If schema privilege inspection, grants, quotas, user creation, or tablespace changes require broader database privileges, stop and route that portion to the DB skill with that skill's required connection/user. + +For documented `APEX_INSTANCE_ADMIN` API ownership, signature checks, and sensitive API classification, use `instance-admin-api.md` before generating executable package calls. + +## Parsing Schema Guardrails + +Only suggest application-owned schemas as APEX parsing schemas. Do not suggest platform, runtime, DBA, or service accounts, even if they technically exist and have `CREATE SESSION`. + +Never suggest these accounts or account families as primary or additional parsing schemas: + +- `PDB_ADMIN` +- `ADMIN` +- `SYS`, `SYSTEM`, `DBSNMP`, `OUTLN`, `GSMADMIN_INTERNAL` +- Oracle-maintained accounts where `ORACLE_MAINTAINED = 'Y'` +- APEX platform schemas such as `APEX_%`, `FLOWS_%`, `APEX_PUBLIC_USER`, `APEX_LISTENER`, `APEX_REST_PUBLIC_USER` +- ORDS schemas such as `ORDS_METADATA`, `ORDS_PUBLIC_USER`, and any `ORDS_%` service/runtime schema +- Runtime or shared service accounts used by ORDS, connection pools, monitoring, CI/CD, or automation +- Personal developer accounts in production + +Prefer schemas created specifically for the application or workspace, for example `SALES_APP`, `SALES_REF`, or `HR_PORTAL_APP`. + +## Find Candidate Schemas + +Use this as a conservative starting point when the user asks which schemas can be mapped. Review the result with the user before creating or changing mappings. + +```sql +SELECT username, + account_status, + authentication_type, + default_tablespace, + created +FROM dba_users +WHERE oracle_maintained = 'N' + AND account_status NOT LIKE 'LOCKED%' + AND username NOT IN ( + 'ADMIN', + 'PDB_ADMIN', + 'APEX_PUBLIC_USER', + 'APEX_LISTENER', + 'APEX_REST_PUBLIC_USER', + 'ORDS_METADATA', + 'ORDS_PUBLIC_USER' + ) + AND username NOT LIKE 'APEX\_%' ESCAPE '\\' + AND username NOT LIKE 'FLOWS\_%' ESCAPE '\\' + AND username NOT LIKE 'ORDS\_%' ESCAPE '\\' +ORDER BY username; +``` + +On environments where `DBA_USERS.ORACLE_MAINTAINED` is not visible, use `ALL_USERS` only as a fallback and apply the same name-based exclusions. When in doubt, ask whether the schema is application-owned before mapping it. + +## Existing Schema Privilege Check + +When the user wants to reuse an existing schema as a primary or additional parsing schema, check its account status, quotas, and current system privileges before mapping it. Do not assume an existing user is suitable just because it exists. + +```sql +SELECT username, + account_status, + authentication_type, + default_tablespace, + temporary_tablespace, + oracle_maintained +FROM dba_users +WHERE username = UPPER(:schema_name); +``` + +```sql +SELECT privilege +FROM dba_sys_privs +WHERE grantee = UPPER(:schema_name) +ORDER BY privilege; +``` + +```sql +SELECT tablespace_name, + bytes, + max_bytes +FROM dba_ts_quotas +WHERE username = UPPER(:schema_name) +ORDER BY tablespace_name; +``` + +Evaluate the result against the application need. Typical APEX application parsing schemas may need narrowly scoped object-creation privileges such as `CREATE TABLE`, `CREATE VIEW`, `CREATE SEQUENCE`, `CREATE PROCEDURE`, `CREATE TRIGGER`, `CREATE TYPE`, and quota on the application tablespace. The standard APEX-managed grant path is `APEX_INSTANCE_ADMIN.ADD_SCHEMA(..., p_grant_apex_privileges => TRUE)`, which applies privileges from `APEX_GRANTS_FOR_NEW_USERS_ROLE` in releases that support it. That role may include database-version-specific privileges such as `CREATE MLE` and `EXECUTE DYNAMIC MLE`. Schemas should not receive broad administrative grants such as `DBA`, `SELECT ANY TABLE`, `EXECUTE ANY PROCEDURE`, `CREATE ANY TABLE`, `GRANT ANY ROLE`, or `GRANT ANY PRIVILEGE` for ordinary workspace creation. + +If required privileges are missing or existing privileges are too broad, stop before mapping the schema and ask: + +```text +The existing schema does not match the expected privilege profile for this APEX workspace. Do you want me to route the privilege adjustment through db/security/privilege-management.md before continuing? +``` + +If privileges are correct, continue with the workspace creation or schema mapping. Do not generate GRANT or REVOKE statements from this APEX skill; route generic database privilege changes to `db/security/privilege-management.md`. + +## APEX-Managed Schema Grants + +For APEX releases where `APEX_INSTANCE_ADMIN.ADD_SCHEMA` exposes `p_grant_apex_privileges`, use APEX-managed schema privilege grants as the standard for new database users/schemas that will be used as APEX workspace or parsing schemas: + +```sql +BEGIN + APEX_INSTANCE_ADMIN.ADD_SCHEMA( + p_workspace => :workspace_name, + p_schema => :schema_name, + p_grant_apex_privileges => TRUE); +END; +/ +``` + +This option grants the standard APEX privileges for a workspace schema, including privileges from `APEX_GRANTS_FOR_NEW_USERS_ROLE` in APEX releases that support that role. It is the APEX-owned equivalent of the Administration Services "Grant APEX Privileges" behavior. Use it unless the user or environment policy explicitly opts out. Do not rely on the package default; installed package specs can default `p_grant_apex_privileges` to `FALSE`, so pass `TRUE` explicitly when standard APEX grants are required. + +Before using the parameter, verify the installed APEX package signature. `APEX_INSTANCE_ADMIN` may be a synonym for the real APEX package, such as `WWV_FLOW_INSTANCE_ADMIN`, so resolve the synonym instead of checking only `PACKAGE_NAME = 'APEX_INSTANCE_ADMIN'`: + +```sql +WITH apex_instance_admin_target AS ( + SELECT owner, + object_name AS package_name + FROM all_objects + WHERE object_name = 'APEX_INSTANCE_ADMIN' + AND object_type = 'PACKAGE' + UNION ALL + SELECT table_owner AS owner, + table_name AS package_name + FROM all_synonyms + WHERE synonym_name = 'APEX_INSTANCE_ADMIN' +) +SELECT DISTINCT + a.owner, + a.package_name, + a.object_name, + a.overload, + a.sequence, + a.position, + a.argument_name, + a.in_out, + a.data_type, + a.defaulted +FROM apex_instance_admin_target t +JOIN all_arguments a + ON a.owner = t.owner + AND a.package_name = t.package_name +WHERE a.object_name = 'ADD_SCHEMA' +ORDER BY a.owner, + a.package_name, + a.overload, + a.sequence; +``` + +If permissions allow, inspect the standard APEX role contents before and after provisioning: + +```sql +SELECT privilege +FROM sys.dba_sys_privs +WHERE grantee = 'APEX_GRANTS_FOR_NEW_USERS_ROLE' +ORDER BY privilege; +``` + +If `p_grant_apex_privileges` is absent, use the older `ADD_SCHEMA` signature and route any missing privilege remediation to `db/security/privilege-management.md`. Do not invent manual grants in this APEX skill. If a schema is already mapped by `ADD_WORKSPACE`, do not blindly call `ADD_SCHEMA` for the same schema; verify the mapping and privileges, then route missing manual remediation to the DB skill when the supported APEX API path is unavailable. + +## Add Schema Mapping + +Add an existing schema to a workspace with supported APEX APIs. + +```sql +BEGIN + APEX_INSTANCE_ADMIN.ADD_SCHEMA( + p_workspace => :workspace_name, + p_schema => :schema_name, + p_grant_apex_privileges => TRUE); +END; +/ +``` + +Check package signatures first: + +```sql +WITH apex_instance_admin_target AS ( + SELECT owner, + object_name AS package_name + FROM all_objects + WHERE object_name = 'APEX_INSTANCE_ADMIN' + AND object_type = 'PACKAGE' + UNION ALL + SELECT table_owner AS owner, + table_name AS package_name + FROM all_synonyms + WHERE synonym_name = 'APEX_INSTANCE_ADMIN' +) +SELECT DISTINCT + a.owner, + a.package_name, + a.argument_name, + a.position, + a.data_type, + a.defaulted +FROM apex_instance_admin_target t +JOIN all_arguments a + ON a.owner = t.owner + AND a.package_name = t.package_name +WHERE a.object_name = 'ADD_SCHEMA' +ORDER BY a.owner, + a.package_name, + a.position; +``` + +## Export And Import + +For application imports into a target workspace, use the deployment skill for `APEX_APPLICATION_INSTALL`, build options, substitution strings, credential references, and safe import validation. + +DB skill in use: `db/devops/schema-migrations.md` for generic schema migration governance. The APEX workspace skill is being used for workspace-to-schema mapping. + +DB skill in use: `db/security/privilege-management.md` for generic grants and database object privileges. The APEX workspace skill is being used only to decide which application-owned schemas may be mapped to a workspace. + +Use `references/deployment/` for APEX application export/import and environment promotion details. + +## Guardrails + +- Parsing schemas are not personal interactive logins in production. +- Do not write directly to internal APEX repository tables. +- Keep workspace schema mapping separate from generic object privileges. +- Review APEX exports before sharing; they may contain URLs, authorization schemes, build options, static files, credential references, defaults, and business logic. diff --git a/apex/admin/references/workspace/security-review.md b/apex/admin/references/workspace/security-review.md new file mode 100644 index 0000000..1ed2376 --- /dev/null +++ b/apex/admin/references/workspace/security-review.md @@ -0,0 +1,17 @@ +# APEX Workspace Security Review + +Use this checklist after substantial workspace provisioning, import/export, schema mapping, resource governance, or removal work. + +- Scope: the workflow stayed APEX-specific; generic privilege, auditing, security, SQL tuning, ASH/AWR, SQLcl, ORDS, or resource diagnosis was routed to the relevant `db/...` skill with a visible `DB skill in use:` message. +- APEX admin identity: every live MCP-backed workspace step used the confirmed APEX admin identity, not `SYS`, `SYSDBA`, a parsing schema, workspace user, ORDS/APEX runtime account, generic deployment user, or unknown account. If `SYSTEM` was used, the exact uppercase `YES` confirmation, scope, targets, and risk summary were recorded before workspace work continued. +- Protocol file: workspace provisioning, removal, user changes, schema mapping, and debugging workflows created or updated a local protocol file outside the skill tree before the work began. +- DB handoff identity: every generic DB step used the selected DB skill's required connection/user rather than silently reusing the APEX admin connection. +- Licensed diagnostics: AWR and ASH usage called out Diagnostics Pack requirements before historical database-performance views were used. +- Provisioning side effects: `WORKSPACE_PROVISION_DEMO_OBJECTS` was checked before workspace creation, and any demonstration applications/database objects were explicitly desired or explicitly prevented. +- Privileges: parsing schemas, workspace administrators, developers, database-login users, ORDS/APEX runtime accounts, and DBA/admin accounts are separate and least-privilege. +- Broad grants: no ordinary APEX provisioning grants `DBA`, `SELECT ANY TABLE`, `EXECUTE ANY PROCEDURE`, `CREATE ANY TABLE`, `GRANT ANY ROLE`, or `GRANT ANY PRIVILEGE`. +- Supported interfaces: workspace changes use supported APEX APIs and views, not direct writes to internal APEX repository tables. +- Version and cloud limits: APEX package signatures, view columns, Autonomous Database limits, and managed-service restrictions were checked before version-specific SQL or PL/SQL. +- Secrets and exports: workspace exports, scripts, logs, and examples do not expose real passwords, tokens, SMTP credentials, wallet passwords, web credentials, or secret-bearing URLs. +- Destructive actions: affected workspaces, schemas, APEX users, database users, and tablespaces are listed; protected accounts are blocked; explicit confirmation is required. +- Data exposure: logs, Team Development files, exports, and session context avoid unnecessary payload columns, BLOBs, CLOBs, request values, and sensitive metadata. diff --git a/apex/admin/references/workspace/users-and-auth.md b/apex/admin/references/workspace/users-and-auth.md new file mode 100644 index 0000000..3f109bf --- /dev/null +++ b/apex/admin/references/workspace/users-and-auth.md @@ -0,0 +1,76 @@ +# APEX Workspace Users And Authentication + +Use this topic for initial workspace administrators, developers, end users, and `Database Username` builder-login environments. + +If the user asks for an APEX Instance Administrator, APEX Administration Services administrator, or an admin user for the `INTERNAL` workspace, stop using this topic and route to `references/deployment/instance-admin-bootstrap.md`. That bootstrap path uses `apxchpwd.sql`; it is not a normal workspace-scoped `APEX_UTIL.CREATE_USER` operation. + +For documented `APEX_INSTANCE_ADMIN.CREATE_OR_UPDATE_ADMIN_USER` or `APEX_INSTANCE_ADMIN.UNLOCK_USER` requests, load `instance-admin-api.md` first. Do not use those APIs for initial `INTERNAL` Instance Administrator bootstrap unless the Oracle-supported environment path explicitly calls for them. + +Use `APEX_WORKSPACE_APEX_USERS` when you need supported workspace-user metadata for administrators, developers, and end users. Check column availability first on older or managed APEX environments. + +MCP-backed workspace-user reads or changes must use the confirmed APEX admin identity from `apex/admin/SKILL.md`. Do not create, unlock, reset, or inspect APEX workspace users under `SYS`, `SYSDBA`, parsing schemas, workspace users, ORDS/APEX runtime accounts, generic deployment users, or unknown accounts. `SYSTEM` is allowed only after the exact uppercase `YES` confirmation required by the APEX Admin Identity Gate. + +## Temporary Password Policy + +If the user provides an approved secret-handling method, use that. + +If the user wants the agent to create a newly created APEX workspace user through MCP-backed automation, do not ask the user to send the password in chat. First confirm the environment, username, email, role, and secret-handling path. + +For demo or test workflows only, the user may explicitly approve the temporary fallback password `Welcome!123`. Always set `p_change_password_on_first_use => 'Y'`. + +Before using the fallback, require this confirmation: + +```text +I will create APEX user in workspace with the temporary demo/test password Welcome!123 and force password change on first login. Confirm this is a non-production demo/test environment and reply exactly: YES, use the temporary demo password. +``` + +After creating a user with the fallback password, tell the user: + +```text +APEX user was created with the temporary demo/test password Welcome!123 and must change it on first login. +``` + +Do not use the fallback password silently. Do not use it for production, shared non-test environments, or customer environments. + +## Create Initial Workspace Admin + +Set the workspace security group ID before creating workspace-scoped users outside an APEX session. + +```sql +DECLARE + l_workspace_id NUMBER; +BEGIN + l_workspace_id := APEX_UTIL.FIND_SECURITY_GROUP_ID(:workspace_name); + APEX_UTIL.SET_SECURITY_GROUP_ID(l_workspace_id); + + APEX_UTIL.CREATE_USER( + p_user_name => :apex_user_name, + p_email_address => :email_address, + p_web_password => :temporary_password, + p_developer_privs => 'ADMIN:CREATE:DATA_LOADER:EDIT:HELP:MONITOR:SQL', + p_change_password_on_first_use => 'Y'); + + COMMIT; +END; +/ +``` + +Do not include real production passwords in skills, examples, logs, scripts, or chat output. + +## Database-Username Builder Login + +If the APEX sign-in page says `Database Username`, a matching database user may be required in addition to the APEX workspace user. Keep the security contexts separate: + +- Workspace Admin +- Developer +- End User +- Parsing Schema +- Database Login User +- ORDS/APEX Runtime Accounts +- DBA/Admin Accounts + +DB skill in use: `db/admin/user-management.md` and `db/security/privilege-management.md` for generic database user creation and privilege management. The APEX workspace skill is being used for APEX login-model and workspace-user context. + +After this handoff, use the selected DB skill's required connection/user for database-login user creation, grants, password policy, quotas, and privilege remediation. Do not reuse the APEX admin connection unless the DB skill explicitly accepts it. + +Do not grant `DBA`, `SELECT ANY TABLE`, `EXECUTE ANY PROCEDURE`, `CREATE ANY TABLE`, `GRANT ANY ROLE`, or `GRANT ANY PRIVILEGE` for ordinary APEX workspace users. diff --git a/apex/admin/references/workspace/version-notes.md b/apex/admin/references/workspace/version-notes.md new file mode 100644 index 0000000..cb0d3a7 --- /dev/null +++ b/apex/admin/references/workspace/version-notes.md @@ -0,0 +1,137 @@ +# APEX Workspace Version Notes + +APEX version is usually more important than Oracle Database version for these APIs. The same database release can host different supported APEX versions, and APEX package signatures can change independently of database release cadence. + +Before citing API signatures or version-specific behavior, use official Oracle APEX documentation. Start with APEX 26.1: + +```text +https://docs.oracle.com/en/database/oracle/apex/26.1/htmrn/ +https://docs.oracle.com/en/database/oracle/apex/26.1/htmig/ +https://docs.oracle.com/en/database/oracle/apex/26.1/aeapi/ +``` + +Use Oracle's APEX support table for current support status: + +```text +https://www.oracle.com/apex/ +``` + +As of June 3, 2026, Oracle's published support matrix lists: + +| Release | General Availability | Support Ends | +| --- | --- | --- | +| 26.1 | May 2026 | November 2027 | +| 24.2 | January 2025 | July 2027 | +| 24.1 | June 2024 | December 2026 | +| 23.2 | November 2023 | May 2026 | + +Treat `23.2` as expired for active MCP-backed APEX admin workflows after May 2026. Use it only for explicitly requested legacy-version migration or compatibility analysis. + +Use APEX 24.2 or APEX 24.1 documentation only when the installed or target environment is that APEX release: + +```text +https://docs.oracle.com/en/database/oracle/apex/24.2/ +https://docs.oracle.com/en/database/oracle/apex/24.1/ +``` + +Do not use APEX documentation older than 24.1 unless the user explicitly asks for legacy-version migration or compatibility analysis. If the target version is unknown, use APEX 26.1 as the default reference and keep SQL version-tolerant. + +## No Database Access + +When no live database connection is available, ask the user for the installed or target APEX version before making version-sensitive recommendations. + +If the user does not know the version, continue only with version-tolerant static guidance: + +- use APEX 26.1 documentation as the default reference; +- do not claim a specific view, column, package argument, or behavior exists in the target instance; +- mark final SQL/API calls as pending verification against `APEX_RELEASE`, `APEX_DICTIONARY`, `ALL_TAB_COLUMNS`, and `ALL_ARGUMENTS`; +- do not generate state-changing SQL or PL/SQL until the supported-version gate can be verified. + +## Supported Version Gate + +Run this gate before any MCP-backed APEX admin workflow. Continue only when the +active connection has passed the APEX Admin Identity Gate in `apex/admin/SKILL.md` +and the installed APEX version is in the supported list. As of June 2026, this +skill supports APEX `26.1`, `24.2`, and `24.1`. + +```sql +SELECT version_no, + CASE + WHEN REGEXP_LIKE(version_no, '^(26\.1|24\.2|24\.1)(\.|$)') + THEN 'SUPPORTED' + ELSE 'UNSUPPORTED' + END AS apex_admin_skill_support +FROM apex_release; +``` + +If `APEX_ADMIN_SKILL_SUPPORT` is `UNSUPPORTED`, stop before generating SQL, +PL/SQL, monitoring queries, deployment steps, workspace changes, or import +instructions. + +Use this message: + +```text +Unsupported APEX version detected: . The APEX admin skill supports only currently supported APEX releases: 26.1, 24.2, and 24.1 as of June 2026. I will stop before generating APEX admin SQL or change steps for this environment. +``` + +Use these checks before generating version-sensitive SQL. `APEX_INSTANCE_ADMIN` may be a synonym for the real APEX package, so resolve it before checking arguments: + +```sql +SELECT version_no +FROM apex_release; + +WITH apex_instance_admin_target AS ( + SELECT owner, + object_name AS package_name + FROM all_objects + WHERE object_name = 'APEX_INSTANCE_ADMIN' + AND object_type = 'PACKAGE' + UNION ALL + SELECT table_owner AS owner, + table_name AS package_name + FROM all_synonyms + WHERE synonym_name = 'APEX_INSTANCE_ADMIN' +) +SELECT DISTINCT + a.owner, + a.package_name, + a.object_name, + a.argument_name, + a.position, + a.data_type, + a.defaulted +FROM apex_instance_admin_target t +JOIN all_arguments a + ON a.owner = t.owner + AND a.package_name = t.package_name +WHERE a.object_name IN ('ADD_WORKSPACE', 'ADD_SCHEMA') +ORDER BY a.owner, + a.package_name, + a.object_name, + a.position; +``` + +Use `ALL_TAB_COLUMNS`, `ALL_ARGUMENTS`, `APEX_DICTIONARY`, and supported APEX version views before relying on a column or package parameter. + +## APEX Diff Helper + +APEX Diff can be used as a convenience helper when comparing APEX Dictionary +views and public PL/SQL APIs across APEX releases, including current releases +such as APEX 26.1 when they are listed there: + +```text +https://apexadb.oracle.com/ords/r/apexdiff/apex_diff/home +``` + +Use it to identify likely standard-view, standard-call, or package-signature +changes before writing monitoring, performance, deployment, or workspace SQL. +Then verify the installed target instance with `APEX_RELEASE`, +`APEX_DICTIONARY`, `ALL_TAB_COLUMNS`, and `ALL_ARGUMENTS`. Do not treat APEX +Diff output as a substitute for local metadata checks or official Oracle APEX +documentation. + +For Oracle Database 19c through 26ai, keep workspace provisioning scripts portable by detecting APEX package signatures and by avoiding database-version assumptions unless the task depends on database-specific features such as MLE, Resource Manager setup, or schema privilege syntax. + +DB skill in use: `db/architecture/oracle-cloud-oci.md` or the relevant `db/admin/*` skill only when the question moves into generic database or cloud administration. The APEX workspace skill is being used for APEX version and package signature context. + +After a DB-skill handoff, use the selected DB skill's required connection/user. Do not reuse the APEX admin connection for generic database or cloud administration unless that DB skill explicitly accepts it. diff --git a/apex/admin/tools/apex-export-risk-scan.mjs b/apex/admin/tools/apex-export-risk-scan.mjs new file mode 100755 index 0000000..e8a89cd --- /dev/null +++ b/apex/admin/tools/apex-export-risk-scan.mjs @@ -0,0 +1,304 @@ +#!/usr/bin/env node + +import { promises as fs } from "node:fs"; +import path from "node:path"; + +const DEFAULT_MAX_EXAMPLES = 12; + +const SIGNALS = [ + { + id: "apex_collection", + label: "APEX Collections", + pattern: /\bAPEX_COLLECTIONS?\b/i, + risk: "Session-scoped Collection work can lengthen APEX requests when large data sets are materialized or repeatedly refreshed." + }, + { + id: "wait_for_result", + label: "Synchronous Dynamic Actions", + pattern: /p_wait_for_result\s*=>\s*'Y'/i, + risk: "Synchronous PL/SQL Dynamic Actions hold the browser flow and the APEX request until server work completes." + }, + { + id: "ajax_submit", + label: "AJAX Items To Submit", + pattern: /p_ajax_items_to_submit/i, + risk: "Many AJAX submits can multiply APEX requests for one user action or page load." + }, + { + id: "execute_plsql_da", + label: "Execute PL/SQL Dynamic Actions", + pattern: /NATIVE_EXECUTE_PLSQL_CODE/i, + risk: "PL/SQL Dynamic Actions can become request hot spots when fired frequently or chained." + }, + { + id: "explicit_commit", + label: "Explicit COMMIT", + pattern: /^\s*COMMIT\s*;/i, + risk: "Explicit commits inside APEX page processing split transaction control and can complicate error handling." + }, + { + id: "dynamic_sql", + label: "Dynamic SQL", + pattern: /\bEXECUTE\s+IMMEDIATE\b/i, + risk: "Dynamic SQL in APEX components needs review for parse cost, bind usage, and predictable request timing." + }, + { + id: "temporary_lob", + label: "Temporary CLOB/BLOB", + pattern: /\bDBMS_LOB\.CREATETEMPORARY\b/i, + risk: "Temporary LOB creation in an APEX request can indicate large generated responses or payload processing." + }, + { + id: "htp_output", + label: "Direct HTP Output", + pattern: /\bHTP\.P\b/i, + risk: "Direct generated output can indicate custom AJAX or JSON endpoints that should be measured for size and timing." + }, + { + id: "apex_web_service", + label: "APEX Web Service Calls", + pattern: /\bAPEX_WEB_SERVICE\./i, + risk: "External calls from APEX requests can make user requests dependent on remote latency." + }, + { + id: "g_x_globals", + label: "APEX_APPLICATION.G_X Globals", + pattern: /\bAPEX_APPLICATION\.G_X\d+\b/i, + risk: "Custom AJAX parameter handling should be checked for validation, data volume, and repeated calls." + }, + { + id: "select_star", + label: "SELECT *", + pattern: /\bSELECT\s+\*/i, + risk: "SELECT * in APEX reports, charts, or callbacks can fetch unnecessary columns and make component cost less predictable." + } +]; + +function usage() { + return `Usage: + node apex/admin/tools/apex-export-risk-scan.mjs --export [--format markdown|json] [--out ] [--max-examples ] + +Purpose: + Static APEX-only export review. This tool does not tune ORDS, SQLcl, database indexes, wait events, or execution plans. +`; +} + +function readOption(args, name, fallback = "") { + const index = args.indexOf(name); + if (index === -1 || index + 1 >= args.length) { + return fallback; + } + return args[index + 1]; +} + +function hasFlag(args, name) { + return args.includes(name); +} + +function countHeaderValue(header, regex) { + const match = header.match(regex); + return match ? match[1].trim() : ""; +} + +function parseNumber(value) { + const normalized = String(value || "").replace(/,/g, "").trim(); + const parsed = Number.parseInt(normalized, 10); + return Number.isFinite(parsed) ? parsed : null; +} + +function parseHeader(lines) { + const header = lines.slice(0, 260).join("\n"); + return { + apex_release: countHeaderValue(header, /p_release\s*=>\s*'([^']+)'/i) || countHeaderValue(header, /--\s+Version:\s+(.+)/i), + import_version_date: countHeaderValue(header, /p_version_yyyy_mm_dd\s*=>\s*'([^']+)'/i), + application_id: countHeaderValue(header, /--\s+Application:\s+([0-9]+)/i) || countHeaderValue(header, /p_default_application_id\s*=>\s*([0-9]+)/i), + application_name: countHeaderValue(header, /--\s+Name:\s+(.+)/i) || countHeaderValue(header, /p_name\s*=>\s*(?:nvl\([^,]+,)?'([^']+)'/i), + export_time: countHeaderValue(header, /--\s+Date and Time:\s+(.+)/i), + exported_by: countHeaderValue(header, /--\s+Exported By:\s+(.+)/i), + app_version: countHeaderValue(header, /p_flow_version\s*=>\s*'([^']+)'/i), + compatibility_mode: countHeaderValue(header, /p_compatibility_mode\s*=>\s*'([^']+)'/i), + counts: { + pages: parseNumber(countHeaderValue(header, /--\s+Pages:\s+([0-9,]+)/i)), + items: parseNumber(countHeaderValue(header, /--\s+Items:\s+([0-9,]+)/i)), + validations: parseNumber(countHeaderValue(header, /--\s+Validations:\s+([0-9,]+)/i)), + processes: parseNumber(countHeaderValue(header, /--\s+Processes:\s+([0-9,]+)/i)), + regions: parseNumber(countHeaderValue(header, /--\s+Regions:\s+([0-9,]+)/i)), + buttons: parseNumber(countHeaderValue(header, /--\s+Buttons:\s+([0-9,]+)/i)), + dynamic_actions: parseNumber(countHeaderValue(header, /--\s+Dynamic Actions:\s+([0-9,]+)/i)), + plugins: parseNumber(countHeaderValue(header, /--\s+Plug-ins:\s+([0-9,]+)/i)), + messages: parseNumber(countHeaderValue(header, /--\s+Messages:\s+([0-9,]+)/i)) + } + }; +} + +function cleanSnippet(line) { + return line + .replace(/(authorization\s*[:=]\s*)\S+/ig, "$1") + .replace(/(bearer\s+)[A-Za-z0-9._~+/-]+=*/ig, "$1") + .replace(/\b([A-Za-z0-9_]*(?:password|passwd|pwd|secret|token|api_key|apikey|client_secret)[A-Za-z0-9_]*)\s*=>\s*'[^']*'/ig, "$1 => ''") + .replace(/\b([A-Za-z0-9_]*(?:password|passwd|pwd|secret|token|api_key|apikey|client_secret)[A-Za-z0-9_]*)\s*=>\s*[^,\s)]+/ig, "$1 => ") + .replace(/\b([A-Za-z0-9_]*(?:password|passwd|pwd|secret|token|api_key|apikey|client_secret)[A-Za-z0-9_]*)\s*[:=](?!>)\s*'[^']*'/ig, "$1=") + .replace(/\b([A-Za-z0-9_]*(?:password|passwd|pwd|secret|token|api_key|apikey|client_secret)[A-Za-z0-9_]*)\s*[:=](?!>)\s*\S+/ig, "$1=") + .replace(/\s+/g, " ") + .trim() + .slice(0, 220); +} + +function contextLabel(context) { + const parts = []; + if (context.page_id) { + parts.push(`page ${context.page_id}`); + } + if (context.page_name) { + parts.push(context.page_name); + } + if (context.component_name) { + parts.push(context.component_name); + } + return parts.join(" / "); +} + +function scan(lines, maxExamples) { + const signalMap = new Map(SIGNALS.map((signal) => [ + signal.id, + { + ...signal, + count: 0, + examples: [] + } + ])); + + const context = { + page_id: "", + page_name: "", + component_name: "" + }; + + for (let index = 0; index < lines.length; index += 1) { + const line = lines[index]; + const lineNumber = index + 1; + + const pagePrompt = line.match(/^prompt\s+PAGE\s+([0-9]+)\s*(?:-\s*(.*))?$/i); + if (pagePrompt) { + context.page_id = pagePrompt[1]; + context.page_name = (pagePrompt[2] || "").trim(); + context.component_name = ""; + } + + const pagePath = line.match(/^prompt\s+--application\/pages\/page_0*([0-9]+)/i); + if (pagePath) { + context.page_id = pagePath[1]; + context.component_name = ""; + } + + const componentName = line.match(/,p_name\s*=>\s*'([^']+)'/i); + if (componentName) { + context.component_name = componentName[1]; + } + + for (const signal of SIGNALS) { + if (!signal.pattern.test(line)) { + continue; + } + const entry = signalMap.get(signal.id); + entry.count += 1; + if (entry.examples.length < maxExamples) { + entry.examples.push({ + line: lineNumber, + context: contextLabel(context), + snippet: cleanSnippet(line) + }); + } + } + } + + return Array.from(signalMap.values()).sort((left, right) => right.count - left.count || left.label.localeCompare(right.label)); +} + +function renderMarkdown(report) { + const lines = []; + lines.push("# APEX Export Runtime Risk Scan"); + lines.push(""); + lines.push("Static APEX-only review. Findings are candidates for APEX follow-up, not proof of runtime root cause."); + lines.push(""); + lines.push("## Export Metadata"); + lines.push(""); + for (const [key, value] of Object.entries(report.metadata)) { + if (key === "counts") { + continue; + } + lines.push(`- ${key}: ${value || "unknown"}`); + } + lines.push(""); + lines.push("## Component Counts"); + lines.push(""); + for (const [key, value] of Object.entries(report.metadata.counts)) { + lines.push(`- ${key}: ${value ?? "unknown"}`); + } + lines.push(""); + lines.push("## Static APEX Signals"); + lines.push(""); + lines.push("| Signal | Count | APEX Review Reason |"); + lines.push("|---|---:|---|"); + for (const signal of report.signals) { + lines.push(`| ${signal.label} | ${signal.count} | ${signal.risk} |`); + } + lines.push(""); + lines.push("## Examples"); + for (const signal of report.signals.filter((item) => item.count > 0)) { + lines.push(""); + lines.push(`### ${signal.label}`); + lines.push(""); + for (const example of signal.examples) { + const suffix = example.context ? ` (${example.context})` : ""; + lines.push(`- line ${example.line}${suffix}: \`${example.snippet.replace(/`/g, "'")}\``); + } + } + lines.push(""); + lines.push("## External Boundary"); + lines.push(""); + lines.push("This tool does not recommend ORDS pool changes, SQLcl workflows, database indexes, wait-event interpretation, or execution-plan tuning. Use these findings to choose APEX Activity Log, Page Performance, Debug, and browser Network verification targets."); + lines.push(""); + return lines.join("\n"); +} + +async function main() { + const args = process.argv.slice(2); + if (hasFlag(args, "--help") || args.length === 0) { + console.log(usage()); + return; + } + + const exportPath = readOption(args, "--export"); + if (!exportPath) { + throw new Error("Missing required --export ."); + } + const format = readOption(args, "--format", "markdown").toLowerCase(); + const outPath = readOption(args, "--out"); + const maxExamples = Number.parseInt(readOption(args, "--max-examples", String(DEFAULT_MAX_EXAMPLES)), 10); + + if (!["markdown", "json"].includes(format)) { + throw new Error("--format must be markdown or json."); + } + + const content = await fs.readFile(exportPath, "utf8"); + const lines = content.split(/\r?\n/); + const report = { + source: path.basename(exportPath), + generated_at: new Date().toISOString(), + metadata: parseHeader(lines), + signals: scan(lines, Number.isFinite(maxExamples) ? maxExamples : DEFAULT_MAX_EXAMPLES) + }; + + const rendered = format === "json" ? JSON.stringify(report, null, 2) + "\n" : renderMarkdown(report); + if (outPath) { + await fs.writeFile(outPath, rendered, "utf8"); + } else { + process.stdout.write(rendered); + } +} + +main().catch((error) => { + console.error(`apex-export-risk-scan: ${error.message}`); + process.exit(1); +}); diff --git a/apex/admin/tools/workspace-admin-plan.mjs b/apex/admin/tools/workspace-admin-plan.mjs new file mode 100755 index 0000000..0339830 --- /dev/null +++ b/apex/admin/tools/workspace-admin-plan.mjs @@ -0,0 +1,437 @@ +#!/usr/bin/env node + +function usage() { + return `Usage: + node apex/admin/tools/workspace-admin-plan.mjs --action [--workspace ] [--schema ] [--user ] [--format markdown|json] + +Purpose: + Generate APEX-only workspace administration checklists and supported APEX view/API snippets. + This tool does not create database users, grant privileges, run SQLcl, or perform database administration. +`; +} + +function readOption(args, name, fallback = "") { + const index = args.indexOf(name); + if (index === -1 || index + 1 >= args.length) { + return fallback; + } + return args[index + 1]; +} + +function hasFlag(args, name) { + return args.includes(name); +} + +function bindValue(value, placeholder) { + return value ? value.toUpperCase() : placeholder; +} + +const APEX_VERSION_GATE_SNIPPET = { + label: "Supported APEX version gate", + sql: `SELECT version_no, + CASE + WHEN REGEXP_LIKE(version_no, '^(26\\.1|24\\.2|24\\.1)(\\.|$)') + THEN 'SUPPORTED' + ELSE 'UNSUPPORTED' + END AS apex_admin_skill_support +FROM apex_release;` +}; + +function inventoryPlan(input) { + return { + title: "APEX Workspace Inventory", + cautions: [ + "Run the supported APEX version gate first; stop if the installed APEX release is unsupported by this skill.", + "Use supported APEX views only.", + "Inspect view columns in the target APEX version before relying on version-specific columns.", + "Do not query or update internal APEX repository tables." + ], + checklist: [ + "Identify the target workspace and workspace ID.", + "List mapped parsing schemas.", + "List workspace administrators and developers.", + "List applications in the workspace.", + "Record any missing or unknown evidence explicitly." + ], + snippets: [ + APEX_VERSION_GATE_SNIPPET, + { + label: "View column check", + sql: `SELECT table_name, + column_id, + column_name, + data_type +FROM all_tab_columns +WHERE table_name IN ( + 'APEX_WORKSPACES', + 'APEX_WORKSPACE_SCHEMAS', + 'APEX_WORKSPACE_APEX_USERS', + 'APEX_APPLICATIONS') +ORDER BY table_name, + column_id;` + }, + { + label: "Workspace inventory", + sql: `SELECT workspace_id, + workspace, + workspace_display_name, + path_prefix, + schemas, + applications, + apex_developers, + apex_workspace_administrators, + created_on +FROM apex_workspaces +WHERE (:workspace_name IS NULL OR workspace = UPPER(TRIM(:workspace_name))) +ORDER BY workspace;` + }, + { + label: "Workspace schema mappings", + sql: `SELECT workspace_name, + schema +FROM apex_workspace_schemas +WHERE (:workspace_name IS NULL OR workspace_name = UPPER(TRIM(:workspace_name))) +ORDER BY workspace_name, + schema;` + }, + { + label: "Workspace users", + sql: `SELECT workspace_name, + user_name, + email, + is_admin, + is_application_developer, + account_locked +FROM apex_workspace_apex_users +WHERE (:workspace_name IS NULL OR workspace_name = UPPER(TRIM(:workspace_name))) +ORDER BY workspace_name, + user_name;` + }, + { + label: "Workspace applications", + sql: `SELECT workspace, + application_id, + application_name, + alias +FROM apex_applications +WHERE (:workspace_name IS NULL OR workspace = UPPER(TRIM(:workspace_name))) +ORDER BY workspace, + application_id;` + } + ], + binds: { + workspace_name: bindValue(input.workspace, ":workspace_name") + } + }; +} + +function createPlan(input) { + return { + title: "APEX Workspace Create Plan", + cautions: [ + "This plan covers only the APEX workspace step.", + "Run the supported APEX version gate first; stop if the installed APEX release is unsupported by this skill.", + "Prefer a dedicated non-SYS/SYSTEM database account granted APEX_ADMINISTRATOR_ROLE for routine APEX workspace automation.", + "Do not connect MCP or routine automation as SYS or SYSDBA for this workflow.", + "SYSTEM without SYSDBA may run APEX-admin-scoped work only after the verified identity, exact scope, risk summary, and an exact uppercase YES confirmation; do not put passwords in logged MCP SQL.", + "Create or update a local operation protocol file outside the skill tree before workspace changes begin.", + "Non-APEX database user creation, password handling, manual grants, tablespaces, and quotas belong outside this APEX admin tool.", + "For new database users/schemas that will become APEX workspace or parsing schemas, use APEX-managed schema grants through APEX_INSTANCE_ADMIN.ADD_SCHEMA p_grant_apex_privileges => TRUE as the standard when the installed APEX version supports that parameter.", + "WORKSPACE_PROVISION_DEMO_OBJECTS is an instance-level side-effect setting; do not change it or create workspaces under the wrong value without explicit user confirmation.", + "Check APEX_INSTANCE_ADMIN.ADD_WORKSPACE and ADD_SCHEMA arguments in the installed APEX version before use." + ], + checklist: [ + "Confirm the installed APEX version is supported by this skill.", + "Check WORKSPACE_PROVISION_DEMO_OBJECTS and confirm whether demonstration applications/database objects should be created in new workspaces.", + "Confirm exact workspace name.", + "Confirm workspace description or administrative notes.", + "Confirm the local protocol output directory or exact Markdown file path.", + "Confirm the active workspace automation account is a dedicated APEX admin identity or SYSTEM approved by the exact uppercase YES gate, and not SYS or SYSDBA.", + "If SYSTEM is used, show the verified identity, exact workspace/API scope, password-handling path when relevant, and risk summary; continue only after the user replies exactly YES.", + "Confirm whether the workspace reuses an existing schema or needs a new database user/schema.", + "For an existing schema, review suggested additional privileges through the schema-mapping reference before mapping it.", + "For supported ADD_SCHEMA signatures, use p_grant_apex_privileges => TRUE as the standard APEX-managed grant behavior unless the user or environment policy opts out; do not rely on the package default.", + "For a new schema, route database user creation, password handling, tablespace, quota, and manual grants to the relevant DB skill before the APEX workspace API step.", + "Confirm primary parsing schema and any additional schema mappings.", + "Verify the schema mapping candidate is not an APEX platform, ORDS, DBA, or shared runtime account.", + "Confirm whether a deterministic workspace ID is required.", + "Confirm the initial workspace administrator details and secret-handling path through the workspace users reference.", + "For bulk provisioning, preview the exact naming method, count or email-address input, quota, Resource Manager consumer group, automatic-purge setting, demo-object policy, and description before any create loop.", + "Create the workspace with supported APEX_INSTANCE_ADMIN API.", + "Verify the workspace through supported APEX views." + ], + snippets: [ + { + label: "Connection identity guard", + sql: `SELECT SYS_CONTEXT('USERENV', 'SESSION_USER') AS session_user, + SYS_CONTEXT('USERENV', 'CURRENT_USER') AS current_user, + SYS_CONTEXT('USERENV', 'ISDBA') AS is_dba +FROM dual;` + }, + APEX_VERSION_GATE_SNIPPET, + { + label: "Demo object provisioning check", + sql: `SELECT APEX_INSTANCE_ADMIN.GET_PARAMETER('WORKSPACE_PROVISION_DEMO_OBJECTS') AS workspace_provision_demo_objects +FROM dual;` + }, + { + label: "ADD_WORKSPACE API argument check", + sql: `WITH apex_instance_admin_target AS ( + SELECT owner, + object_name AS package_name + FROM all_objects + WHERE object_name = 'APEX_INSTANCE_ADMIN' + AND object_type = 'PACKAGE' + UNION ALL + SELECT table_owner AS owner, + table_name AS package_name + FROM all_synonyms + WHERE synonym_name = 'APEX_INSTANCE_ADMIN' +) +SELECT DISTINCT + a.owner, + a.package_name, + a.argument_name, + position, + a.data_type, + a.defaulted +FROM apex_instance_admin_target t +JOIN all_arguments a + ON a.owner = t.owner + AND a.package_name = t.package_name +WHERE a.object_name = 'ADD_WORKSPACE' +ORDER BY a.owner, + a.package_name, + a.position;` + }, + { + label: "ADD_SCHEMA API argument check", + sql: `WITH apex_instance_admin_target AS ( + SELECT owner, + object_name AS package_name + FROM all_objects + WHERE object_name = 'APEX_INSTANCE_ADMIN' + AND object_type = 'PACKAGE' + UNION ALL + SELECT table_owner AS owner, + table_name AS package_name + FROM all_synonyms + WHERE synonym_name = 'APEX_INSTANCE_ADMIN' +) +SELECT DISTINCT + a.owner, + a.package_name, + a.argument_name, + position, + a.data_type, + a.defaulted +FROM apex_instance_admin_target t +JOIN all_arguments a + ON a.owner = t.owner + AND a.package_name = t.package_name +WHERE a.object_name = 'ADD_SCHEMA' +ORDER BY a.owner, + a.package_name, + a.position;` + }, + { + label: "Create workspace", + sql: `BEGIN + APEX_INSTANCE_ADMIN.ADD_WORKSPACE( + p_workspace_id => :workspace_id, + p_workspace => :workspace_name, + p_primary_schema => :primary_schema); +END; +/` + }, + { + label: "Add additional schema mapping with APEX-managed grants", + sql: `-- Use only for a schema that is not already mapped by ADD_WORKSPACE. +BEGIN + APEX_INSTANCE_ADMIN.ADD_SCHEMA( + p_workspace => :workspace_name, + p_schema => :schema_name, + p_grant_apex_privileges => TRUE); +END; +/` + }, + ...inventoryPlan(input).snippets.slice(1, 3) + ], + binds: { + workspace_name: bindValue(input.workspace, ":workspace_name"), + primary_schema: bindValue(input.schema, ":primary_schema"), + schema_name: bindValue(input.schema, ":schema_name"), + workspace_id: ":workspace_id" + } + }; +} + +function verifyPlan(input) { + return { + title: "APEX Workspace Verification", + cautions: [ + "Verification should use supported APEX views and APIs.", + "Do not treat session state or client-side checks as a security boundary." + ], + checklist: [ + "Verify workspace row exists.", + "Verify schema mappings match the intended parsing schemas.", + "Verify the expected APEX workspace users and roles.", + "Verify expected applications are in the workspace.", + "Record unexpected extra mappings, missing users, or locked accounts." + ], + snippets: inventoryPlan(input).snippets, + binds: { + workspace_name: bindValue(input.workspace, ":workspace_name"), + primary_schema: bindValue(input.schema, ":primary_schema"), + user_name: bindValue(input.user, ":user_name") + } + }; +} + +function recoverPlan(input) { + return { + title: "Interrupted APEX Provisioning Recovery", + cautions: [ + "Do not retry blindly after an interrupted APEX provisioning workflow.", + "Inventory planned artifacts first and classify each as created, missing, or unknown.", + "Use the destructive removal workflow only after explicit confirmation." + ], + checklist: [ + "Reconnect or re-establish a fresh APEX evidence source.", + "Inventory the planned workspace.", + "Inventory mapped parsing schemas.", + "Inventory planned APEX workspace users.", + "Inventory planned APEX applications.", + "Ask whether to continue from verified state or remove only the listed artifacts." + ], + snippets: inventoryPlan(input).snippets, + binds: { + workspace_name: bindValue(input.workspace, ":workspace_name"), + primary_schema: bindValue(input.schema, ":primary_schema"), + user_name: bindValue(input.user, ":user_name") + } + }; +} + +function removePlan(input) { + return { + title: "APEX Workspace Removal Pre-Check", + cautions: [ + "Removal is destructive and requires a fresh exact confirmation for the current scope.", + "Default to keeping related database users and tablespaces.", + "Database user and tablespace deletion is outside this APEX admin tool." + ], + checklist: [ + "List the exact workspace to remove.", + "List mapped schemas and applications for user review.", + "Confirm whether only the APEX workspace should be removed.", + "Require the configured confirmation phrase from the removal reference before generating removal steps.", + "Verify removal through supported APEX views." + ], + snippets: [ + ...inventoryPlan(input).snippets.slice(1), + { + label: "APEX workspace removal shape", + sql: `BEGIN + APEX_INSTANCE_ADMIN.REMOVE_WORKSPACE( + p_workspace => :workspace_name, + p_drop_users => 'N', + p_drop_tablespaces => 'N'); +END; +/` + } + ], + binds: { + workspace_name: bindValue(input.workspace, ":workspace_name") + } + }; +} + +function buildPlan(input) { + switch (input.action) { + case "inventory": + return inventoryPlan(input); + case "create": + return createPlan(input); + case "verify": + return verifyPlan(input); + case "recover": + return recoverPlan(input); + case "remove": + return removePlan(input); + default: + throw new Error("--action must be one of inventory, create, verify, recover, remove."); + } +} + +function renderMarkdown(plan) { + const lines = []; + lines.push(`# ${plan.title}`); + lines.push(""); + lines.push("APEX-only workspace administration aid. Review snippets before use in the target APEX version."); + lines.push(""); + lines.push("## Cautions"); + lines.push(""); + for (const caution of plan.cautions) { + lines.push(`- ${caution}`); + } + lines.push(""); + lines.push("## Checklist"); + lines.push(""); + for (const item of plan.checklist) { + lines.push(`- ${item}`); + } + lines.push(""); + lines.push("## Binds"); + lines.push(""); + for (const [name, value] of Object.entries(plan.binds)) { + lines.push(`- ${name}: ${value}`); + } + lines.push(""); + lines.push("## Snippets"); + for (const snippet of plan.snippets) { + lines.push(""); + lines.push(`### ${snippet.label}`); + lines.push(""); + lines.push("```sql"); + lines.push(snippet.sql); + lines.push("```"); + } + lines.push(""); + return lines.join("\n"); +} + +function main() { + const args = process.argv.slice(2); + if (hasFlag(args, "--help") || args.length === 0) { + console.log(usage()); + return; + } + + const input = { + action: readOption(args, "--action"), + workspace: readOption(args, "--workspace"), + schema: readOption(args, "--schema"), + user: readOption(args, "--user") + }; + const format = readOption(args, "--format", "markdown").toLowerCase(); + + if (!["markdown", "json"].includes(format)) { + throw new Error("--format must be markdown or json."); + } + + const plan = buildPlan(input); + if (format === "json") { + process.stdout.write(JSON.stringify(plan, null, 2) + "\n"); + } else { + process.stdout.write(renderMarkdown(plan)); + } +} + +try { + main(); +} catch (error) { + console.error(`workspace-admin-plan: ${error.message}`); + process.exit(1); +}