Details
# Oracle AI Data Platform — Migrator for Databricks (Claude Code plugin)
> **Migrate Databricks notebooks, jobs, and catalogs onto Oracle AIDP — in natural language.**
> Drives the *AIDP Databricks Migration Toolkit* (a Claude-with-tool-use migrator that runs cells live on the AIDP cluster, verifies, and self-fixes) end-to-end from Claude Code.
> **Canonical home:** [`oracle-samples/oracle-aidp-samples/ai/claude-code-plugins/oracle-ai-data-platform-workbench-databricks-migrator`](https://github.com/oracle-samples/oracle-aidp-samples/tree/main/ai/claude-code-plugins/oracle-ai-data-platform-workbench-databricks-migrator).
> End users install via Anthropic's community marketplace (see [Install](#install)).
This plugin is **self-contained** — it ships the full Python migrator engine bundled under `engine/`. After install, skills invoke the engine via `${CLAUDE_PLUGIN_ROOT}/engine/scripts/...` — no separate clone required.
> **Status:** **v0.2.0** — self-contained release (engine bundled).
---
## What it does
| Area | Skills |
|---|---|
| **Bootstrap & setup** | `aidp-migrator-overview`, `aidp-migrator-bootstrap` |
| **Plan & inventory** | `aidp-build-dag`, `aidp-check-data` |
| **Notebook migration** | `aidp-migrate-job`, `aidp-fixup-cell`, `aidp-resume-migration` |
| **Catalog migration** | `aidp-migrate-catalog`, `aidp-bucket-mapping` |
| **Verification & quality** | `aidp-acceptance-contract` |
Each skill is a single-file Markdown SKILL.md with a clear "When to use" trigger so Claude routes correctly without external direction.
### What gets automated end-to-end
```
Databricks workspace AIDP DataLake
───────────────────── ──────────────
Unity Catalog / HMS schemas + tables (DDL) ──┐
│ ├──→ Catalog migration (batched DDL replay)
External s3:// table locations ──┘ 18 rewrite rules:
• 3-part → 2-part name flatten
• s3://→oci:// via bucket-map
• source format preserved (Delta stays Delta)
• delta.* / spark.sql.* catch-all scrub
• MV / streaming rejection
• CREATE SCHEMA COMMENT-colon strip
Notebooks (.dbc + .ipynb + .py) ──→ Notebook migration (per workflow / per task)
Jobs + schedules + task DAGs Pass 1: %run dep tree, code-only rewrites
Pass 2: cell-by-cell execute on AIDP cluster,
4-way verify (status / stderr / Spark
logs / Opus eval), up to 10 fix attempts,
fixup_cell rewind for replays.
Output: per-job .ipynb + JOB_REPORT.md
```
### Signature differentiators
- **Cell-by-cell execute / verify / fix loop** — the migrator runs each Databricks-rewritten cell on a live AIDP cluster, parses the output, and self-corrects via Claude with tool use (14 tools: `explore_path`, `suggest_oci_path`, `search_catalog`, `run_on_cluster`, `describe_table`, `list_schemas_and_tables`, `read_notebook_source`, `inspect_package_source`, `summarize_notebook`, `submit_code`, `make_note`, `get_cell_history`, `get_history_entry`, `fixup_cell`).
- **Write-redirect sandbox schema** — source data is never touched during migration. Every `.saveAsTable(...)` / `INSERT INTO` is silently redirected to a sandbox schema, then verified post-run.
- **Acceptance contract** — for batch / streaming pipelines, declare PASS only after K consecutive empty-pending windows (consecutive-zero convergence).
---
## When to use this plugin
You're moving a Databricks workload onto AIDP and want Claude Code to drive the whole port. Typical asks:
- *"Migrate this Databricks job to AIDP"* / *"port my workflow"*
- *"Build a migration manifest from this Databricks workspace path"*
- *"My migrated notebook fails at cell 23 — fix it"*
- *"Migrate the Unity Catalog DDL into the AIDP default catalog"*
- *"Check whether the source tables are available before I migrate"*
- *"Resume the migration from task X"*
- *"Set up the acceptance contract for the streaming task"*
---
## Install
### Via Anthropic's community marketplace (recommended)
```
/plugin marketplace add anthropics/claude-plugins-community
/plugin install oracle-ai-data-platform-workbench-databricks-migrator
```
> The plugin is published from this canonical Oracle-samples location. Anthropic's community-marketplace bot picks up new oracle-samples plugins on its weekly cadence, so this install command becomes effective ~1 week after merge.
---
## Prerequisites
This plugin is **self-contained** — the full migrator engine (`scripts/`, `aidp_compat/`, schemas, `requirements.txt`, `setup.py`) ships bundled under `engine/`. After install, skills invoke the engine via `${CLAUDE_PLUGIN_ROOT}/engine/scripts/...`. To actually run a migration you still need:
1. **Python deps** — one-time install in any Python 3.10+ environment:
```bash
pip install -r ${CLAUDE_PLUGIN_ROOT}/engine/requirements.txt
```
(Or `cd ${CLAUDE_PLUGIN_ROOT}/engine && pip install -e .`.)
2. **OCI authentication** — `~/.oci/config` with either an `api_key` profile (recommended for unattended runs) or an `oci session authenticate` session-token profile (for interactive notebooks). The engine reads whichever profile you select via `--oci-profile`.
3. **An ACTIVE AIDP cluster** — the engine's Pass-2 execute/verify/fix loop talks to a live cluster via WebSocket. The cluster must be in `Active` state before invoking `job_migrate.py`.
4. **An `ANTHROPIC_API_KEY` env var** — the engine uses Claude with tool use under the hood for each cell rewrite + verify. Each migrated job spends a few minutes of Claude-with-tool-use time.
5. **An `env-coords.md`** — see [references/env-coords.template.md](./references/env-coords.template.md) for the scaffold the skills thread through (DataLake OCID, workspace UUID, cluster ID, AIDP base URL, OCI profile name).
Once those are in place, the plugin's skills know how to invoke each entrypoint — Claude Code will run the right CLI commands in the right order based on your natural-language ask.
---
## Skill index
### Foundation
| Skill | Purpose |
|---|---|
| `aidp-migrator-overview` | Router. Read this first to get the lay of the toolkit + which skill handles which phase. |
| `aidp-migrator-bootstrap` | One-shot environment readiness check (Python deps, OCI auth, cluster state, env-coords file). |
### Plan
| Skill | Purpose |
|---|---|
| `aidp-build-dag` | Build a migration manifest (`reports/<job>_manifest.json`) from a Databricks workspace path. Walks `%run` chains, emits the execution DAG. |
| `aidp-check-data` | Pre-migration scan: verify source tables / paths exist on the AIDP cluster before kicking off. |
### Execute
| Skill | Purpose |
|---|---|
| `aidp-migrate-job` | Run the migrator end-to-end against a manifest. Pass-1 deps + Pass-2 cell-by-cell on the live cluster. |
| `aidp-fixup-cell` | Targeted rewind: re-execute cells from history index N with a `why` reason, through execute+verify+fix. |
| `aidp-resume-migration` | Resume an interrupted run. Skips already-migrated notebooks via `_migration_cache` + on-cluster `os.path.exists()`. |
### Catalog
| Skill | Purpose |
|---|---|
| `aidp-migrate-catalog` | Extract Unity Catalog / HMS metadata → 18-rule DDL rewriter → batched replay on AIDP. |
| `aidp-bucket-mapping` | Configure `s3://` → `oci://` bucket/namespace mappings the rewriter consumes. |
### Verify
| Skill | Purpose |
|---|---|
| `aidp-acceptance-contract` | YAML-driven consecutive-zero-window acceptance for batch / streaming convergence. |
### Slash commands (interactive flows)
| Command | What it does |
|---|---|
| `/migrate-job` | Guided full-job migration flow (DAG → check-data → migrate → status). |
| `/migrate-catalog` | Guided catalog migration (extract → rewrite preview → batched replay). |
| `/check-data` | Pre-migration data-availability scan. |
| `/migration-status` | Parse + summarize a `JOB_REPORT.md` from a previous run. |
### Specialist agents (for parallel review)
| Agent | What it does |
|---|---|
| `databricks-notebook-analyzer` | Reads a Databricks notebook + reports what it does, dependencies, risks (drives the migrator's Pass-1 planning). |
| `migration-reviewer` | Reviews a migrated `.ipynb` for correctness post-Pass-2 (Apache Spark API drift, %run trailing-slash, builtins.sum shadow, etc.). |
### References (loaded on demand)
| Reference | Use |
|---|---|
| [`references/ddl-rewrite-rules.md`](./references/ddl-rewrite-rules.md) | The 18 DDL rewrite rules the catalog migrator applies, with input/output examples. |
| [`references/gotchas.md`](./references/gotchas.md) | 15 Databricks → AIDP gotchas + fix recipes. |
| [`references/env-coords.template.md`](./references/env-coords.template.md) | Scaffold for your environment coordinates (DataLake OCID, workspace UUID, etc.). Fill once, refer to in every skill. |
| [`references/job-report-format.md`](./references/job-report-format.md) | How to parse `JOB_REPORT.md` to extract per-cell pass/fail/fix counts. |
| [`references/cli-map.md`](./references/cli-map.md) | Each migrator CLI entrypoint mapped to its purpose + canonical invocation. |
---
## Engine
Everything flows through the migrator's CLI:
```bash
# Inventory & plan
python3 ${CLAUDE_PLUGIN_ROOT}/engine/scripts/build_dag.py --root <workspace-path> --job-name <name> --output reports/<name>_manifest.json
python3 ${CLAUDE_PLUGIN_ROOT}/engine/scripts/check_data_availability.py --root <workspace-path> --cluster <cluster-id>
# Execute
export ANTHROPIC_API_KEY=sk-ant-...
python3 ${CLAUDE_PLUGIN_ROOT}/engine/scripts/job_migrate.py \
--manifest reports/<name>_manifest.json \
--cluster <cluster-id> \
--aidp-base https://aidp.<region>.oci.oraclecloud.com/20240831 \
--datalake-ocid <your-datalake-ocid> \
--workspace-id <your-workspace-uuid> \
--output-base <output-workspace-path> \
--oci-profile <profile-name>
# Catalog (separate flow)
python3 ${CLAUDE_PLUGIN_ROOT}/engine/scripts/extract_catalog_databricks.py --catalogs <catalog> --schemas-only "<catalog>:<schema>" --out reports/catalog_pack.json
python3 ${CLAUDE_PLUGIN_ROOT}/engine/scripts/migrate_catalog.py --pack reports/catalog_pack.json --cluster <cluster-id> --aidp-base ... --datalake-ocid ...
```
The skills tell Claude when to call each + how to thread args from the env-coords reference into them.
The one script that talks to Databricks, `extract_catalog_databricks.py`, reads the PAT from
`DATABRICKS_TOKEN` in the environment or from `--token-file <path>` (a file only its owner can
read -- `chmod 600`; on Windows the permission check is skipped); the other scripts
(`build_dag_from_workflow.py`, `migrate_catalog.py`, ...) talk to AIDP with your OCI profile, not
to Databricks. No script takes a credential on the command line: `--token <value>` is refused
with exit code 2, because argv is visible in `ps`, shell history, CI transcripts and pasted
support commands, and a mistyped form (`--tok=<value>`, `-t <value>`, a bare value) is refused
without the value being repeated in the error. Output names where the token came from, never
the token.
---
## Runtime safety: notebook sandbox policy and secrets
The bundled `aidp_compat` layer that migrated notebooks import on the cluster enforces two
fail-closed controls at runtime (in addition to the static cell analysis and write redirects
the migrator applies while it drives the cluster):
**Notebook sandbox policy** (`aidp_compat.notebook_policy`). `dbutils.notebook.run(...)` and
the compat write helpers (`dbutils.fs.rm/mv/cp/put/mkdirs`, `safe_io.safe_*` writers) refuse to
run until a sandbox is declared for the run:
| Variable | Meaning |
|---|---|
| `AIDP_SANDBOX_CATALOG` / `AIDP_SANDBOX_SCHEMA` | The only catalog.schema that table writes may target |
| `AIDP_SANDBOX_PREFIX` | Comma list of prefixes that path writes, `dbutils.fs` deletes/moves, `os` / `shutil` / `pathlib` file operations and absolute `open()` calls must stay under; the first entry is the object-storage prefix (`oci://bucket@ns/path/`), the rest are staging areas. Paths are canonicalised; `..` segments and (on POSIX) symlinks leading outside are always outside |
| `AIDP_SANDBOX_ALLOW_NETWORK` | `1` permits network imports (`requests`, `socket`, `urllib`, `urllib3`, `httpx`, `aiohttp`, `http.client`, `paramiko`, `ftplib`, `smtplib`, ...); default off |
| `AIDP_NOTEBOOK_POLICY_ALLOW` | Comma list of rule ids that are a reviewed exception (for example `NBP-TABLE-DYNAMIC` for a `saveAsTable` target that cannot be resolved statically) |
| `AIDP_NOTEBOOK_POLICY_LOG` | Optional JSONL file that receives every refusal / allowed exception / sandbox declaration |
`job_migrate.py` declares the sandbox automatically on every cluster connect and per task: the
write-redirect schema and bucket, plus the staging areas its own migration rules steer
notebooks into (`/Volumes/default/default/dbfs/` for translated `/dbfs/` paths, `/tmp/` for
torch / h5py / sqlite staging) and the tool's output directory. An operator-provided value wins
and replaces the whole list. The first declaration is frozen for the kernel: later environment
changes are ignored by the runtime assertions and a redeclaration from notebook code is refused
(`NBP-POLICY-TAMPER`). Before each non-magic cell runs, the cell is parsed and refused with a
`PermissionError` naming the notebook path, cell index, rule id and remediation if it imports
process / network modules (`subprocess`, `multiprocessing`, `ctypes`, `pty`, `socket`,
`requests`, `urllib`, ...), touches `os.environ` / `os.getenv` / `os.system` / `os.popen` /
`os.exec*` / `os.fork` (also through an alias such as `import os as o`), calls `shutil.rmtree`,
`eval` / `exec` / `compile` / `__import__`, reaches for `importlib` / `builtins` /
`sys.modules` / `getattr(os, ...)`, imports or rebinds the compat shims or the policy module
itself, or opens / removes / renames / writes (`open`, `pathlib`, `os.remove`, `shutil.move`,
`saveAsTable`, `insertInto`, `writeTo`, `df.write.*` including `option("path")`, `CREATE TABLE`
/ `INSERT` / `DROP` / `MERGE` / `DELETE` / `LOCATION` / `OPTIONS (path ...)` via `spark.sql`,
`dbutils.fs.rm/mv/cp/put/mkdirs`) a target outside the sandbox. The gate is deny-by-default for
every route to the same capability, not only the direct spelling: the builtins namespace through
`__builtins__` / `builtins` / `globals()` / `locals()` / `vars()` / `getattr`, `getattr` /
`setattr` with a non-literal name, dunder and frame introspection chains (`__subclasses__`,
`__globals__`, `__dict__`, `f_globals`, ...; `NBP-DUNDER-ESCAPE`), the IPython shell API and
`%magic` / `!command` lines inside a cell (`get_ipython().system`, `InteractiveShell`;
`NBP-IPYTHON-ESCAPE`), the Spark JVM / py4j bridge (`spark._jvm`, `sc._jsc`, `df._jdf`, `py4j`;
`NBP-POLICY-TAMPER`), deserialisers that execute code (`pickle.loads`, `yaml.load` without a
safe loader, `torch.load` without `weights_only=True`; `NBP-DESERIALIZE`), process / debugger /
profiler modules, the stdlib open-equivalents (`io.open`, `os.open`, `gzip.open`, ...), and
names that were bound to any of these and later rebound to something the gate cannot resolve.
The same rule table serves every spelling: `posix` / `nt` are judged as `os`, `getattr(mod,
"literal")` like `mod.literal`, and `str.format` / `format_map` templates (literal or bound once)
are walked field by field (`{0.__class__.__mro__}` refused, `{0.__class__.__name__}` fine).
Library readers (`pd.read_csv`, `spark.read.csv`, `np.load`, `sc.textFile`, ...) with a literal
local path (`/etc/passwd`, `/dbfs/...`, `~`, `C:\`, `file://`) outside the prefix are refused.
`spark.sql` is an allowlist, not a blocklist: only read statements (`SELECT` / `VALUES` / `TABLE`
/ `WITH .. SELECT` / `SHOW` / `DESCRIBE` / `EXPLAIN` / `CACHE` / `UNCACHE` / `REFRESH TABLE` /
`CREATE TEMP VIEW`) and writes to tables inside the sandbox schema are accepted; the top-level
verb is resolved behind a `WITH` CTE list (so `WITH x AS (..) INSERT INTO prod.t` is the write it
is), `reflect(` / `java_method(` / `try_reflect(` (plain or as a backtick-quoted function name) and
`TRANSFORM .. USING` are refused anywhere in a statement, path tables (``<provider>.`<path>` `` for
any provider, quoted or a provider class) and `COPY INTO .. FROM` sources on the local filesystem
outside the prefix are refused, raw literals (`r'..'`) are lexed as Spark lexes them, the
destination of `ALTER .. RENAME TO` is a write target, `spark.sql` keyword arguments are rendered
into the statement as pyspark renders them, `IDENTIFIER(..)` is refused, network data sources
(`USING jdbc` / `kafka` / `socket`, `spark.read.format("jdbc")`, `spark.read.jdbc`) are refused
while the sandbox allows no network access, and `ADD JAR`, `CREATE FUNCTION`, `GRANT`, `SET` outside
a short conf allowlist, SQL scripting, multi-statement texts and every other verb are
`NBP-SQL-REFUSED`. The Python twins (`spark.table`, `spark.catalog.setCurrentCatalog` /
`setCurrentDatabase`, `spark.conf.set`, `spark.catalog.createTable`, `sc.addFile`,
`pyspark.sql.functions.reflect` / `java_method` / `call_function`) are judged by the same rules.
While `dbutils.notebook.run` executes, a runtime SQL guard re-classifies the final text of every
`spark.sql` (after keyword rendering) / `spark.table` / `selectExpr` / `filter` / `where` /
`functions.expr` / `functions.reflect` / `java_method` / `call_function` call before Spark sees it,
and `spark.newSession()` / `getOrCreate()` / `getActiveSession()` are refused because a fresh
session would not carry it.
A target that is a name bound once to a string literal earlier in the run is checked as that
literal; any other non-literal target is refused unless its rule id is allowlisted, with two
scope decisions that are allowed and recorded in the policy log instead: a reader path the gate
cannot resolve (`spark.read.parquet(src)`, `unverified_read_path`; reading source data through
parameters is the normal migration case and object-storage / catalog reads are never
path-checked) and a `spark.sql` statement with run-time fragments whose literal head verb is a
read verb (`unverified_sql_read`; admitted only inside `dbutils.notebook.run`, where the runtime
SQL guard re-classifies the final text before Spark executes it; a bare static scan refuses it as
`NBP-SQL-DYNAMIC`), plus a `DataFrame.pipe(fn)` whose callable the gate cannot type, on a receiver
the notebook bound (`unverified_pipe_callable`; `RDD.pipe(cmd)`, any string-typed `.pipe()`
argument and a receiver the notebook never bound are refused). `open(path_var)` is not such a
decision: a non-literal `open()` path is refused in read mode as well, and so is
`thing.open(path_var)` on a receiver the notebook never bound (`fs.open(p)` on a bound
object-store filesystem is recorded). The review-derived gap classes are closed as classes, not spellings: a gated
module or Spark object handed around as a value (`[os][0]`, `run(os)`, `return os`,
`lambda: os`, ...), a process sink name on a receiver the gate cannot resolve
(`helper().system`, `obj.popen`), string-keyed accessors (`operator.attrgetter` /
`methodcaller`, `functools.reduce(getattr, ..)`, `inspect.getattr_static` / `getmembers`),
re-rooting at a module named mid-chain (`shutil.os.system`, `pd.io.common.os.environ`),
deny-by-default deserialisers (the whole pickle family except the dump side, `torch.load` at
any depth, `numpy` `allow_pickle`, every unsafe yaml loader / constructor / hook / subclass),
`globals()[k]` with a tainted key or a dereferenced result, and `open(*a, **kw)`. The coverage
round on top of that: a list literal is folded into a path only while its name is used for
nothing but `sep.join(name)` (`p[0] = '/etc'`, `p.insert(..)`, `q = p`, `mutate(p)` make the
join dynamic, fail closed); keyword-gated loaders fail closed when the switch is positional or
hidden (`np.load(p, None, True)`, `np.load(p, **kw)`, `torch.load(.., pickle_module=..)` even
with `weights_only=True`, `torch.serialization.add_safe_globals`); the state of a gated module
is read-only (`yaml.SafeLoader.yaml_constructors[..] = h`, `.update(..)`, `setattr(yaml.SafeLoader,
..)`; `sys.path` and `torch` flags stay settable); a process sink name (`mymod.system`) or a
`_private` attribute (`mymod._run`, `np._core`) on an imported module the gate has no rules for
is refused (`platform.system()` is the documented homonym); `site` / `pip` load code from a path
and are refused like `addPyFile`. Library writers are the mirror of the readers and fail
closed like every other write: `np.save`, `torch.save`, `joblib.dump`, `scipy.io.savemat`,
`cv2.imwrite`, `plt.savefig`, `pq.write_table`, `pd.ExcelWriter`, `mlflow.*.save_model`, and
`df.to_csv` / `to_parquet` / `to_pickle` / `write_parquet` / `savefig` / `tofile` on any receiver
with a literal local path outside the prefix are `NBP-PATH-WRITE`, with a path the gate cannot
resolve `NBP-PATH-WRITE-DYNAMIC` (a `StringIO` / `BytesIO` / `ExcelWriter` handle the notebook
bound is not a path); generic `wb.save(..)` / `model.save(..)` / `img.save(..)` judge a literal
path only. `tempfile` creators with a literal `dir=` or an absolute `prefix=` outside the prefix
(and `tempfile.tempdir =`) are `NBP-FS-PATH`; `faulthandler`, `traceback.walk_stack` /
`walk_tb`, `capture_locals=True` and `Task.get_stack()` are frame dumps (`NBP-INDIRECT`). A
`DataFrameWriter` / `DataFrameReader` held in a variable (`wr = df.write.mode('overwrite')`,
`w2 = wr`, `rd = spark.read.format('csv')`) is followed like the chain it was built from, also
across cells; structured-streaming writers (`df.writeStream...start(p)` / `.toTable(t)` /
`.option('checkpointLocation', p)`) are judged like `df.write`; a re-export back to the chain's own
root (`os.path.os.system`, also via `import os.path as op`) is re-rooted like `shutil.os`; and
`http.server` / `wsgiref.simple_server` / the Python web servers are network modules at every door
(`import http; http.server.HTTPServer(..)` included). The gate
matches these forms statically and is not a Python sandbox: a static AST gate over a full
Python runtime is a mitigation layer, the platform-level control is the IAM scope of the
cluster the notebook runs on, and the runtime assertions in `dbutils.fs.*`, `safe_io` and
`dbutils.secrets` are the enforcement layer for writes that go through the compat helpers (see
`engine/aidp_compat/SUPPORTED_OPERATIONS.md` section 8 for the rule table, what is not covered
and the known false refusals). Refusals, allowed exceptions and skipped magic-led cells are
recorded and rendered into each task's test report under **Notebook Policy Log**. Scheduled
jobs that keep using `aidp_compat` after
migration must declare the same variables in their environment.
**Secrets** (`dbutils.secrets`). Lookups go to OCI Vault only (`AIDP_VAULT_OCID`, secret named
`<scope>/<key>`). The plaintext demo fallbacks (`AIDP_SECRET_<SCOPE>_<KEY>` environment
variables and the JSON file named by `AIDP_SECRETS_FILE`) are consulted only when
`AIDP_ALLOW_PLAINTEXT_SECRETS=1`; the file must be owner-only (`0600`) on POSIX, and the shim
logs one line (`insecure plaintext secrets mode active`, never a value) when the mode is on.
`AIDP_SECRET_SCOPES=<scope,scope>` and `AIDP_SECRET_KEYS=<scope/key,scope/*,...>` restrict
what `get` / `list` / `listScopes` may touch (`none` = nothing). `job_migrate.py` derives both
from the `dbutils.secrets.get(scope, key)` literals it finds while planning each task and
declares them in the cluster bootstrap (an operator-provided value wins; a scope used with a
non-literal key is planned as `scope/*`, a non-literal scope must be allowlisted by the
operator). Refusals name the scope/key only and appear in the Notebook Policy Log as
`NBP-RUNTIME-SECRET`; list operations return names only.
---
## Privacy
This plugin **does not collect, store, transmit, or share any user data**. Everything runs locally against **your own** AIDP tenancy. Full statement: [`PRIVACY.md`](./PRIVACY.md).
---
## License
MIT — see [`LICENSE`](./LICENSE).
## Core developers
- **Sid Rao** (Oracle Agentic AI Development)
- **Ahmed Awan** (Oracle Forward Deployed Engineering)
- **Nishant Patel** (Oracle Forward Deployed Engineering)
## skills/aidp-acceptance-contract/SKILL.md
---
name: aidp-acceptance-contract
description: YAML-driven acceptance contract for batch and streaming pipelines that need convergence verification, not just "no exceptions". Declares PASS only after K consecutive zero-result windows (consecutive-zero-window convergence). Use for streaming jobs, slowly-draining backfills, or any pipeline whose success is "the pending queue is empty".
---
# `aidp-acceptance-contract` — convergence verification for batch/streaming jobs
A "no exception" pass is not enough for streaming or backfill pipelines. They might still be processing rows that haven't drained yet. This skill wires up a YAML-driven contract: PASS only after K consecutive empty-pending windows.
## When to use
- Source pipeline is **structured streaming** (the migrator's Pass-2 returns when the trigger completes, but the stream itself hasn't necessarily drained).
- Source pipeline is a **slowly-draining batch backfill** (each task processes a partition, the workflow PASSes when the partition is processed but a separate retry queue holds the failed rows).
- User asks "wait for it to settle", "convergence", "acceptance test on convergence".
**Not needed** for plain ETL where success = "the saveAsTable finished".
## The pattern
```
1. Migrator runs Pass-2 to completion.
2. Acceptance contract starts probing periodically (every `sleep_between_s` seconds).
3. Each probe runs `pending_count_sql` and checks `pending = 0`.
4. After `zero_window` consecutive zero-probes → declare PASS.
5. If we hit `max_attempts` without convergence → declare ACCEPTANCE_CONTRACT_VIOLATED.
Overall migration result is demoted to FAIL.
```
## YAML contract format
Save at `reports/<MyJob>_acceptance.yaml`:
```yaml
# Acceptance contract for <task_key>
task_key: "<task_key>"
description: "Wait until the retry queue drains"
pending_count_sql: "SELECT COUNT(*) AS pending FROM <sandbox_schema>.<retry_queue_table> WHERE status = 'PENDING'"
zero_window: 3 # K consecutive zero windows required for PASS
sleep_between_s: 30 # seconds between probes
max_attempts: 60 # ceiling; 60 × 30s = 30-min hard cap
# Optional: override the cluster (default = use job_migrate's cluster)
cluster_id: null
# Optional: notify-on-violation hook (called once if max_attempts hit before convergence)
on_violation_log_path: "/tmp/<MyJob>_acceptance.log"
```
## Wire into a migration
The contract is loaded by `job_migrate.py` automatically if the YAML exists alongside the manifest:
```bash
# Convention: <MyJob>_manifest.json + <MyJob>_acceptance.yaml side by side
ls reports/
# → reports/<MyJob>_manifest.json
# → reports/<MyJob>_acceptance.yaml
python3 ${CLAUDE_PLUGIN_ROOT}/engine/scripts/job_migrate.py \
--manifest reports/<MyJob>_manifest.json \
--acceptance-contract reports/<MyJob>_acceptance.yaml \
# + the rest of the args
```
If `--acceptance-contract` is omitted, the contract is skipped (default behavior — PASS = Pass-2 cells all green).
## Per-task vs job-wide
The YAML's `task_key` field scopes the contract to ONE task in the manifest. If you have multiple tasks needing convergence, write a list:
```yaml
contracts:
- task_key: "<task_a>"
pending_count_sql: "SELECT COUNT(*) FROM <schema>.<queue_a> WHERE pending"
zero_window: 3
sleep_between_s: 30
max_attempts: 60
- task_key: "<task_b>"
pending_count_sql: "SELECT COUNT(*) FROM <schema>.<queue_b> WHERE pending"
zero_window: 5
sleep_between_s: 60
max_attempts: 30
```
Contracts run sequentially after their respective tasks complete.
## How to read the verdict
After a run, `JOB_REPORT.md` will include an acceptance-contract section:
```
## Acceptance contracts
| task_key | status | windows_observed | converged_at |
|---|---|---|---|
| <task_a> | PASS | 3 consecutive zeros | 2026-XX-XX HH:MM:SS |
| <task_b> | ACCEPTANCE_CONTRACT_VIOLATED | 60 attempts, 0 consecutive zeros | -- |
```
If ANY contract is VIOLATED, the overall `RESULT:` line is demoted from `PASS` to `ACCEPTANCE_CONTRACT_VIOLATED` regardless of cell-level success.
## Building a good `pending_count_sql`
Some rules of thumb for the query:
- Read from a sandbox table you control (most likely the redirect-schema version of the source's queue / retry table).
- The query must return a single column of integer count (the framework specifically reads column "pending" or position 0).
- The query must be FAST — it runs every `sleep_between_s`. Add appropriate filters / partitions.
- The query must be IDEMPOTENT — running it doesn't mutate state.
Example shapes:
```sql
-- Streaming retry queue
SELECT COUNT(*) AS pending
FROM <sandbox_schema>.<retry_queue_table>
WHERE status IN ('PENDING','RETRYING')
AND ingest_ts > current_date - INTERVAL 1 DAY
-- Backfill progress
SELECT (target_count - processed_count) AS pending
FROM <sandbox_schema>.backfill_progress
WHERE backfill_id = '<id>'
-- Streaming watermark gap
SELECT GREATEST(
0,
CAST((unix_timestamp(current_timestamp()) - unix_timestamp(max(event_ts))) / 60 AS INT)
) AS pending
FROM <sandbox_schema>.<streaming_output_table>
```
## What this skill does NOT do
- Doesn't actually run the streaming job — the underlying job_migrate.py already executed the cells. The contract is a POST-execution verification step.
- Doesn't define what "convergence" means semantically — that's the user's `pending_count_sql`.
- Doesn't retry failed cells — it only signals "the pipeline didn't drain in time". For cell-level retries use [`aidp-fixup-cell`](../aidp-fixup-cell/SKILL.md).
## After this
- If PASS: proceed with downstream verification, sign off the migration.
- If VIOLATED: investigate the queue. Either (a) the underlying job needs more time (bump `max_attempts`), (b) the queue is genuinely stuck (data issue, scheduler issue), or (c) the contract is wrong (check the SQL).
## skills/aidp-bucket-mapping/SKILL.md
---
name: aidp-bucket-mapping
description: Configure the s3:// → oci:// bucket / namespace mapping the migrator uses to rewrite paths during notebook + catalog migration. Use when (a) the user has external tables / files at s3:// paths that need to land on OCI Object Storage, OR (b) check_data_availability reports "S3 bucket X not found in OCI bucket mapping", OR (c) DDL rewriter logs a missing-bucket warning.
---
# `aidp-bucket-mapping` — wire up `s3://` ↔ `oci://`
Several places in the migrator look up `s3://<bucket>/<path>` and rewrite to `oci://<bucket>@<namespace>/<path>`:
- `aidp-migrate-catalog` rewrites external-table `LOCATION` clauses.
- `aidp-migrate-job` Pass-1 rewrites `spark.read.parquet("s3://...")` literals in notebook cells.
- `aidp-check-data` probes paths via the same translation.
All consult the same bucket-mapping config.
## When to use
- Setting up the migrator on a new workstation / new tenancy combo.
- Any time a tool reports `S3 bucket "<name>" not found in OCI bucket mapping. Known buckets: [...]`.
- After provisioning a new OCI Object Storage bucket that mirrors a Databricks-side S3 bucket.
## The config file
The migrator loads bucket mappings via the `load_bucket_mapping()` helper. The customer supplies a JSON file with this shape (file path is configurable via `--bucket-mapping`):
```json
{
"buckets": {
"<s3-bucket-name>": {
"oci_bucket": "<oci-bucket-name>",
"oci_namespace": "<oci-namespace>",
"notes": "optional human note"
},
"<another-s3-bucket>": {
"oci_bucket": "<another-oci-bucket>",
"oci_namespace": "<oci-namespace>"
}
},
"default_namespace": "<oci-namespace>",
"default_region": "<oci-region>"
}
```
| Field | Meaning |
|---|---|
| `buckets.<s3-name>.oci_bucket` | Target OCI Object Storage bucket. |
| `buckets.<s3-name>.oci_namespace` | OCI tenancy namespace (NOT the DataLake namespace — these can differ). |
| `default_namespace` | Used when a path references an `oci://` URL without an explicit `@<ns>`. |
| `default_region` | Used to construct the OCI client. |
Save the file to a path the user controls (gitignored — it contains tenancy-specific identifiers). Pass via `--bucket-mapping <path>` to every migrator entrypoint.
## Building the mapping for a new tenancy
If the user is doing this for the first time:
1. **List the source S3 buckets referenced in the Databricks workspace.** Quick way:
```bash
# On the migrator repo:
grep -roE 's3://[a-z0-9.-]+' <source-databricks-checkout>/ | sort -u
```
Or use the migrator's prep helper if available.
2. **For each, identify the target OCI bucket + namespace.** Either:
- The user provisions matching OCI buckets (recommended for big migrations — preserves bucket names).
- The user routes everything into a single shared OCI bucket with prefix isolation.
3. **Find the OCI namespace.** Each OCI tenancy has ONE namespace per region — find it via:
```bash
oci os ns get --profile <profile>
# returns: {"data": "<your-namespace>"}
```
4. **Write the JSON** and place it at `config/bucket_mapping.json` (or wherever your team stores secrets). Make sure it's gitignored.
5. **Test the mapping** by re-running [`aidp-check-data`](../aidp-check-data/SKILL.md) with `--bucket-mapping <path>`. Any `MISSING` entries with `s3://...` paths now resolve to `oci://...` and probe correctly.
## When the mapping should fail FAST (vs warn)
Behavior contract:
- `migrate_catalog.py` REJECTS unknown buckets when `--catalog-manifest` is explicit (data-correctness gate).
- `job_migrate.py` Pass-1 surfaces unknown buckets in the cell-fix Claude context so the model can either route to a synthetic stub OR ask the user.
- `check_data_availability.py` reports unknown-bucket as a hard `MISSING` row.
If you see WARNINGS but the migration continues, that's usually safe — the rewriter passed the path through unchanged. Confirm the consumer notebook either no longer reads that path OR has been adapted.
## Common mistakes
| Mistake | Fix |
|---|---|
| Confusing DataLake namespace vs OCI tenancy namespace | These can differ. `oci_namespace` in the mapping is the TENANCY namespace (`oci os ns get`), not the DataLake's internal namespace. |
| Hardcoding bucket names that include `s3://` prefix | Don't include `s3://` — just the bucket name. |
| Forgetting to pass `--bucket-mapping <path>` to subsequent invocations | The path is per-run, not persisted. Add it to your `aidp-migrate-job` / `aidp-migrate-catalog` invocations. |
| Listing buckets the user doesn't actually have read access to | The mapping resolves the name; access errors surface at first read. Don't pre-mock buckets the user can't touch. |
## After this
- Re-run [`aidp-check-data`](../aidp-check-data/SKILL.md) — any `MISSING` rows that were due to bucket-map issues should now be `OK`.
- Proceed to [`aidp-migrate-job`](../aidp-migrate-job/SKILL.md) / [`aidp-migrate-catalog`](../aidp-migrate-catalog/SKILL.md).
## skills/aidp-build-dag/SKILL.md
---
name: aidp-build-dag
description: Build a migration manifest (the execution DAG) from a Databricks workspace path or workflow ID. Walks %run dependency chains, captures dbutils.notebook.run invocations, and emits reports/<job>_manifest.json — the input every other execute-skill consumes. Use when the user wants to see what would migrate, or before invoking aidp-migrate-job for the first time on a new workload.
---
# `aidp-build-dag` — build the migration manifest
The execution DAG is what the migrator reads to know which notebooks to migrate, in what order, with what dependencies. Build it once per workload.
## When to use
- User asks "what would migrate", "show me the dependency tree", "build the manifest".
- Before any [`aidp-migrate-job`](../aidp-migrate-job/SKILL.md) invocation against a new workload.
- After changing the Databricks workspace path or workflow ID.
## Two entry points
The migrator ships two DAG builders. Pick based on input shape:
| Input | Entrypoint |
|---|---|
| **Path-based**: a folder of `.ipynb` / `.py` notebooks the user wants migrated | `${CLAUDE_PLUGIN_ROOT}/engine/scripts/build_dag.py` |
| **Workflow-based**: a Databricks Job ID whose tasks the user wants migrated, preserving the task DAG | `${CLAUDE_PLUGIN_ROOT}/engine/scripts/build_dag_from_workflow.py` |
## Path-based invocation
```bash
python3 ${CLAUDE_PLUGIN_ROOT}/engine/scripts/build_dag.py \
--root "<databricks-workspace-path>" \
--job-name "<MyJob>" \
--output reports/<MyJob>_manifest.json
```
- `--root` — Databricks workspace folder containing the entry notebooks. The script walks every `*.ipynb` / `*.py` under this prefix.
- `--job-name` — a name for the manifest (used as the output-base subdirectory).
- `--output` — manifest write path.
The builder follows `%run` chains AND `dbutils.notebook.run(...)` calls to build a topo-ordered DAG. It also flags transitive deps so Pass-1 knows which notebooks to migrate code-only first.
## Workflow-based invocation
```bash
python3 ${CLAUDE_PLUGIN_ROOT}/engine/scripts/build_dag_from_workflow.py \
--job-id <databricks-job-id> \
--output reports/<MyJob>_manifest.json
```
This pulls the Job's task definitions via the Databricks Jobs REST API and converts `depends_on` task edges into the manifest's DAG. Use when the user wants the AIDP migration to mirror the Databricks Workflow shape (vs. just inferring dependencies from `%run`).
Required env / args:
- `DATABRICKS_HOST` — `https://<workspace>.cloud.databricks.com`
- `DATABRICKS_TOKEN` — a PAT with workspace-read permission
## Manifest shape
The output is JSON with this top-level structure:
```json
{
"job_name": "<MyJob>",
"tasks": [
{
"task_key": "extract",
"notebook_path": "Users/.../extract.ipynb",
"depends_on": []
},
{
"task_key": "transform",
"notebook_path": "Users/.../transform.ipynb",
"depends_on": ["extract"]
}
],
"deps": [
{
"notebook_path": "Users/.../helpers/io_utils.ipynb",
"referenced_by": ["extract", "transform"]
}
]
}
```
`tasks` are the named entry points; `deps` are `%run` / `notebook.run` targets discovered transitively. Pass-1 migrates the `deps` first (code-only), then Pass-2 executes the `tasks` in topo order.
## Sanity-check the manifest before running
After the builder finishes, do these three reads — small, fast, catch most config issues:
```bash
# 1. count
jq '.tasks | length, .deps | length' reports/<MyJob>_manifest.json
# 2. topo correctness — no cycles, deps come before users
jq '.tasks[] | select(.depends_on | length > 0) | {task: .task_key, deps: .depends_on}' reports/<MyJob>_manifest.json
# 3. notebook paths resolve (every path is reachable from the Databricks workspace)
jq -r '.tasks[].notebook_path' reports/<MyJob>_manifest.json
```
If any `notebook_path` doesn't exist in Databricks, the builder logs a warning but does NOT fail. Catch it here.
## Known caveats
- **`dbutils.notebook.run` with dynamic paths.** If the source notebook builds the target path at runtime (`dbutils.notebook.run(some_var, ...)`), the builder cannot resolve it. The dep won't appear in the manifest and the runt