/agami-core:agami-connect [sample | reintrospect | profile NAME]from agami-core
End-to-end database connection for agami: sets up credentials, introspects live DB into a validated semantic model, enriches with LLM descriptions/entities/metrics, and seeds NL→SQL examples. Run on first install, schema changes, or when asked to connect/introspect.
Ships in agami-core. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Before suggesting any slash command in chat, read shared/invocation-conventions.md. Agami slash commands: /agami-connect, /agami-query, /agami-model, /agami-save-correction, /agami-reconcile. (/agami-model is also the trust-review surface — its Review tab absorbed the former /agami-review.) Never write the un-prefixed forms (/init, /connect, etc.) or colon forms (/agami:connect) — those don't exist. For chat replies, prefer natural language ("say 'reload the schema'", "say 'introspect my database'") — the when_to_use matcher routes correctly without an explicit slash command.
You are setting up the agami semantic model for the user's database. Goal: by the end there is a validated semantic model at <artifacts_dir>/<profile>/ (datasource.yaml + subject_areas/<area>/… + datasources/<connection>/storage.yaml), a seeded examples library at <artifacts_dir>/<profile>/prompt_examples/<area>/examples.yaml, an datasource.md the user can edit, and the user has seen one demo query execute end-to-end.
The structural model is built by a deterministic engine, not hand-authored. sm introspect (run as Phase 1.7 shows) introspects the live DB across all supported dialects — PostgreSQL (incl. Supabase / Redshift), MySQL/MariaDB, Snowflake, BigQuery, SQL Server, Oracle, Databricks, Trino/Presto, DuckDB, SQLite — into the model: storage connection, proposed subject areas, tables, columns + types, primary-key grain, foreign-key relationships with join cardinality, column_groups on wide tables, and sensitive flags on PII. When the catalog (information_schema / PRAGMA / data-dictionary) is reachable it runs in catalog mode; when a locked-down role denies the catalog it falls back per-capability to probe mode (describe via a zero-row header, infer types from a value sample, grain from uniqueness probes, FKs from name+overlap) and everything inferred lands unreviewed for sign-off. Your job is the layer the engine can't do: enrichment (prose descriptions, entities, metrics, caveats) and curation (subject-area boundaries, trust review).
If an sm call exits 12, agami's library is older than the plugin: run bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" install (the person approves it), then repeat the call. It is not "no model" (exit 3): never send the person to agami-connect for it.
For the model format: semantic_model/__init__.py (layout) and the Pydantic models in packages/agami-core/src/semantic_model/models.py.
For credentials: shared/credentials-format.md.
For connection method + local execution: shared/connection-reference.md.
For DB error classification: shared/db_error_classifier.md.
For every decision card and result table: shared/question-cards.md.
shared/question-cards.md rule 7). Use (Recommended) only when there's a genuine recommendation. For fact-of-environment questions ("which database type?", "which schemas?"), don't mark any option Recommended — the user picks what they have.AskUserQuestion cannot be submitted with zero boxes checked, so any multiSelect where "pick nothing" is a valid answer MUST offer a selectable "Nothing — continue" (or "Keep everything") option. Never phrase the prompt as "leave all unchecked" — that's unsubmittable and traps the user.shared/question-cards.md rule 9): a card asks only what the data means to the business, in plain words with an example. Batches, --append, --no-safety, mapping thresholds and the like are yours to decide, conservatively, and to report in one line. A card never names a file or table without saying what it is. Before signing answers that came back the same down a whole column of a page or sheet, confirm in one line (rule 10).✓ Introspected 12 tables, ✓ Validator passed, ✓ Generated 10 examples).This is a multi-phase skill, with cards in between. The very first action on every invocation is to show the onboarding steps as a task list, and to keep it current, so the person always knows where they are and what's left. Once the database's folder exists, the list is drawn from sm steps, which prints every step with its status and its numbers read from disk; how and when to run it, and where the list goes, is in shared/task-list.md. Each phase below marks its own step when it starts and ends.
The same steps every run, in the person's words (no "introspect", "enrich" or "NL→SQL"):
1. Connect your database
2. Tell agami about your data
3. Pick the tables
4. Read the tables and joins
5. Describe columns and add metrics
6. Answer what the data can't settle
7. Sign off definitions and hide personal data
8. Write and check example questions
9. Check your reports
10. Summary and first question
Leave out a step that won't run (6 when "Ask me as you go" wasn't picked in 1.5; 9 when no reports were shared in 1.5; 3 with a model spec workbook, which names the tables): mark it skipped, and sm steps leaves it out of the list; never add your own working steps to this list. When a step finishes, add its numbers to its label, so the list reads as a running summary: "Read the tables and joins — 21 tables, 19 joins", "Describe columns and add metrics — 93% described, 7 metrics", "Sign off definitions and hide personal data — 5 of 7 signed". The label with its numbers is the step's line in the list that sm steps prints, copied as printed without its mark, never typed by hand and never an estimate; a step with nothing to count keeps its plain label. While a long step runs, its label carries the live count too ("Read the tables and joins — 30 of 52 tables"), from the same line, which sm progress --wait prints in its own list on every pass, so the list shows movement during a wait and not only at the end. Mark each step in progress when it starts and done the moment it ends, exactly one in progress at a time, and keep it in progress while a card for that step is waiting, so the list shows where the person is while they decide.
Don't seed it again if the list already holds these steps (the skill is resuming after a hand-off, a password page or a file wait): run sm steps "<root>" first and show what it prints (shared/task-list.md, resuming). When $ARGUMENTS == reintrospect, the list restarts at the first step this run marks started (step 2, when Phase 1 begins): sm steps reopens that step and every step after it, and keeps the steps before it done.
Run the detection + ask logic from shared/plan-mode-check.md. agami-connect needs Bash (introspection) and Write (model files) — both blocked in plan mode.
If plan mode is active and the user stays in plan mode (or the skill is invoked under plan mode with no prompt): refuse with the one-liner below and end the turn. DO NOT write a plan file. DO NOT call ExitPlanMode.
I can't introspect in plan mode — switch to Auto or Edit Automatically mode (Shift+Tab to cycle) and re-invoke me. Introspection, enrichment, and the demo query all need write access to
<artifacts_dir>/<profile>/.
If plan mode is not active, skip silently.
Non-negotiable. They override every other instruction here when they conflict.
<artifacts_dir>/local/credentials. That file is the sole credential source — there is no env-var bypass. Never connect to anything else. Never probe localhost unless the credentials say so. Never substitute defaults for missing fields.credentials.example file of 0a.4 that the person fills in themselves. If the person types a secret into the chat anyway, don't use or repeat it: say it should not be shared in chat, suggest they change it, and carry on with the page or the file.pgrep, ps, lsof, find /, ls /Applications, no port-listener scans, no testing connections to common hostnames. The only acceptable Bash probes here are which <tool> and bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" -c 'import <module>'.agami-query auto-invokes us and 0a.10 picks the file up.export PGPASSWORD=…, no psql -W <pw>, no heredoc that interpolates a secret. Hosts render Bash calls in chat; anything on the line leaks. Runtime queries use the auth files from scripts/setup_pgauth.py (psql/mysql) or python -m execute_sql (every driver, reads <artifacts_dir>/local/credentials itself). See shared/connection-reference.md → HARD RULES.bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" <verb> … with every path written out in full. Never put a variable assignment, a pipe, ;, &&, a redirect or a filter on the line, and never run two agami commands in one call. A line written any other way always stops to ask the person for permission; written this way agami's own hook approves the read-only commands and scratch files without a prompt, and every other command asks as usual. Read the whole output: the commands print only what you need. Where a command starts with AGAMI_SCRATCH_ONLY=1 (and AGAMI_SQL_MAX_ROWS=200000 before it on discover and introspect), copy that prefix exactly: it holds every file the call names to agami's scratch folder. <root> is the database's model folder, <artifacts_dir>/<profile>, written out in full; the artifacts folder is preflight step 1's artifacts_dir, never read from the pointer file; scratch files go only in <artifacts_dir>/local/tmp/, named agami-…, never /tmp, and are written with the Write tool (shared/invocation-conventions.md). The person's own words (a company name, a description, a question) go to sm through a file the same way (--name-file, --description-file, --question-file), never on the command line.say, post it as written; when it has then, do that next.If you reach for a command that doesn't fit, stop and re-read this section.
Sample-path short-circuit (check FIRST, before resolving any profile). If the user explicitly asked for the sample — $ARGUMENTS is sample, or they said "try the sample" / "I don't have a database" / "use the sample (or example) data" / "demo data" — then bind $PROFILE_NAME = agami-example, $DB_TYPE = sample, and go straight to Phase 0s. Do this regardless of any existing active_profile or onboarded profiles — the sample is a deliberate, explicit choice and must not be intercepted by another profile's credential/existing-model checks. (A returning person also gets "Try the sample data" on the start card in step 1a; this short-circuit covers the request that already says so.) If agami-example is already set up, Phase 0s sends them to the demo. Only fall through to step 1 when there's no sample signal.
Resolve the environment — bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" connect_resolve.py [--db-type <t>] [--profile <p>] prints {data, anomalies} (self-describing JSON): profile, artifacts_dir, the [<profile>] credentials section + chmod, the cached config, interpreter.python3 (the one Python sm, py and the install all use — use it everywhere; what it lacks, core_ready and has_driver say), native tools, and a next decision. Branch on data.next: ready → the start card for a returning person (step 1a); a reload or re-introspect request skips the card and goes straight to Phase 1 with reintrospect; build → the database's credentials are saved but it has no model yet (the build never ran or never finished): there is nothing to ask yet, so show no start card and never offer "Ask a question"; say in one line "<database> is connected but not built yet, so I'll build it now." and go straight to Phase 1 (a fresh build, not reintrospect), unless the request already names another action (the sample, or connecting a different database); promote → run 0a.10 to promote the filled template, then continue; bootstrap → the first-run start card (step 1a), then Phase 0a. On a first-time bootstrap data.profile is null (profile_source: "default") — there's no profile yet, so narrate it without a name: "No credentials yet — first-time setup." (Never say "profile main" — the user names their profile in 0a.3.) Only when data.profile is non-null (a bootstrap for an explicitly-named/env profile) may you name it. Surface anomalies. agami_python_lacks comes first and stops the run: the $AGAMI_PYTHON the person set lacks the model deps or the driver, and agami uses that Python and no other, so say its detail (the path, what it lacks and the exact install line) before anything else, and go no further until they have run it or changed AGAMI_PYTHON; then resolve again. The others (e.g. credentials_world_readable → offer chmod 600; library_older_than_plugin → offer bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" install, or the AGAMI_PYTHON fix it names; agami_python_cannot_be_brought_current → the $AGAMI_PYTHON the user set has no pip and an old or missing agami-core, so say so; env_profile_has_no_model → AGAMI_PROFILE names a database with no model while others have one: say its detail in one line before the start card, and offer the databases it lists rather than a new connection under that name, unless the person asked to connect one). interpreter.chosen_because says why that Python was picked, and a candidate passed over carries a reason; never substitute a missing_fields value — surface "missing field X for profile Y" and stop.
1a. The start card (conventions: shared/question-cards.md). One AskUserQuestion, one question, header Start. Skip it when the request already names the action: $ARGUMENTS is reintrospect or profile NAME, the person asked to reload or re-introspect, to add a new database (go to Phase 0a), or agami-query invoked this skill because a model is missing (go to Phase 0a).
First run (data.next is bootstrap, nothing connected yet). Question: "How do you want to start?" No option is marked Recommended: whether there is a database to connect is a fact about the person's setup.
| label | description | then |
|---|---|---|
Connect a database | Your own database; the password never goes through the chat | Phase 0a |
Try the sample data | A small demo store, no connection needed | Phase 0s |
Connected but not built (data.next is build). No start card: go straight into the build (step 1). A database with no model has nothing to ask, so Ask a question is never offered for it.
Returning (data.next is ready: a database is already connected and built). Question: "What would you like to do?"
| label | description | then |
|---|---|---|
Ask a question (Recommended) | Ask <active database> something | Hand to agami-query. A question typed in "Other" goes straight there. Picked with no text: offer a card of up to 4 questions taken from that database's seed examples (prompt_examples/), with "Other" for their own. |
Reload the schema | Pick up new or changed tables, keeping descriptions, metrics and sign-offs | Phase 1 as reintrospect (the 1.1 Re-introspect path; 2e previews, then writes). |
Connect another database | Add a different database alongside this one | 1.1a first (same company or a different one), then Phase 0a (the new database gets its own name in 0a.3). |
Try the sample data | A small demo store, no connection needed | Phase 0s |
An empty database gets no recommendation to ask it. When every table in the active database's sm model-tree has rows of 0, the first option is Ask a question without "(Recommended)", its description says " has no rows, so answers will be empty", and Connect another database is marked (Recommended) instead.
Route "Other" text by what it asks for. An action goes to that action: re-introspect, reload or refresh the schema → Reload the schema; add a schema that lives in the same database → Reload the schema with the schema selection in 1.3 widened to the old and new schemas (see the note under 1.1: same database, another schema is a re-introspect, never a new database); review or sign off the model, edit descriptions, exclude tables → agami-model; add or connect a different database → Connect another database; answer the open questions, or what the data can't settle → 2g on the active database. Only a question goes to agami-query. When the text could be either (a schema name alone, say), ask which with a card rather than guess.
This card replaces the 1.1 menu for a returning person; don't ask 1.1 again after it.
Say "database", never "profile", in the card and around it.
Update-check (best-effort). Run the probe from shared/version-check.md; surface a one-liner if a newer version exists. Never block on network failure.
If $ARGUMENTS is reintrospect: re-introspect from scratch, but preserve hand-edits (descriptions, entities, metrics, caveats, trust sign-offs). The engine writes the structural skeleton; merge it over the existing enrichment rather than discarding it (see Phase 2's reintrospect note).
Runs when preflight step 1 returns next: bootstrap (no credentials for the profile) and the person picked "Connect a database", or when they picked "Connect another database". If <artifacts_dir>/local/credentials already has the [<profile>] section for the database being connected, skip Phase 0a entirely.
Two paths, chosen by the operating system, which the session's environment already names (the platform: darwin is macOS, win32 is Windows, linux is Linux); don't run a command to find it:
keyring) and the artifacts folder in place, which is why 0a.5–0a.8 run before it.token, and the page stores a password): the file. 0a.0 → 0a.5b → 0a.6 → 0a.1 → 0a.2 → 0a.3 → 0a.4 (credentials.example) → 0a.5 → 0a.7 → 0a.8 → 0a.9 (a card waits for the filled-in file) → 0a.10 → Phase 1.First, before the database-type card, say in one short message what helps to have to hand, so nobody is asked mid-build for something they could have fetched up front. None of it is required:
Before we connect, it helps to have these to hand (none is required):
- What your organisation does, in a sentence or two.
- What system the data comes from (a product such as ServiceNow or Salesforce, or your own application), and anything about the database: when your fiscal year starts, what currency amounts are in, whether the warehouse already controls who sees personal data.
- Definitions of the tables and columns: a data dictionary, a spec workbook, a dbt or LookML project.
- Definitions of your metrics and business terms.
- The questions people ask. They become checked examples, and how many of them agami answers correctly is how you can tell the model is right.
Then ask 1 and 2 as their own first questions, on one card (two questions; leave the Company one out when it was already authored, as 1.4 A says):
Company card, asked here instead of after the connection. 1.4 A says what to write, and it is written once the folder exists (below).Source: "What system does this data come from? Add anything about the database too, e.g. "ServiceNow; fiscal year starts in July; amounts in USD". Type it in Other." Options: Our own application (built in-house, no product dictionary) and Not sure (agami reads the database and works it out). No option is marked Recommended: it is a fact about their setup.Both answers are hints, never copied verbatim into the model. They steer the descriptions written in Phase 2 (a domain prior, like the narrative) and switch on product-specific help; no description, glossary entry or rule is the person's sentence pasted in.
Hold the answers; write nothing yet. At this point there is no artifacts folder (0a.6 picks it) and no interpreter (0a.5 finds it), so sm can't run. Bind them now and write each where the list below says: the company and the personal-data setting right after 0a.8, when the folder and the interpreter exist; the fiscal year after 1.7, when datasource.yaml exists. Bind the Source answer:
$SOURCE_SYSTEM. When agami has a metadata preset for it (ServiceNow: servicenow), 2a.0 passes --preset servicenow to sm enrich-metadata, which reads the product's dictionary and choice tables straight from the database without modelling them. So never add the preset's source tables (sys_dictionary, sys_choice, or a warehouse copy under another name) to 1.6's kept set: 2a.0's enrich-metadata --preset <name> reads them directly, and kept they are modelled as ordinary tables. And 1.5's published-product-schema path is already on. Say it in one line: "ServiceNow: I'll read its own data dictionary for the column meanings."$FISCAL_START_MONTH (1 to 12). After 1.7 write it with bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" set-fiscal-year "<root>" --month <month>, the same write 1.4 D makes, and skip 1.4 D's card. Anything vaguer ("our year is odd") is not a month: 1.4 D asks it.$CURRENCY_HINT, a hint only: nothing is written now. 2d offers it as the currency for the money columns sm suggest-units finds (sm set-units --currency <ISO code>), and the person still agrees to that plan there.bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" set-personal-data "<artifacts_dir>" enforced_by_warehouse. It is a build-only setting, kept in <artifacts_dir>/local/.config and never deployed. The build then flags nothing personal and Phase 4 skips the personal-data question. Say it in one line. set-personal-data "<artifacts_dir>" flagged_by_agami undoes it (a reload flags again).Items 3 to 5 are handed over on 1.5's context card (its Definitions or a semantic layer and Questions people ask options); the questions people ask go to <artifacts_dir>/local/tmp/agami-asked-questions.txt and become checked examples in Phase 5, as they do today. Don't ask for them here.
When Phase 0a is skipped (the credentials already exist), ask this step at the start of 1.4 instead, on a first onboard of that database. Not on reintrospect.
<artifacts_dir>/local/<artifacts_dir> is settled by now: 0a.6 chose it on a first run and saved it with sm choose-folder, and otherwise it is the resolve step's data.artifacts_dir. One call creates the folder, its private local/ (0700) and scratch folder, and makes <artifacts_dir>/.gitignore ignore local/ (no Write, Read or mkdir of your own):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" init-local "<artifacts_dir>"
It works only on agami's own artifacts folder: an error naming another folder means 0a.6's choose-folder call hasn't run. It never installs anything: exit code 12 means agami's library isn't installed yet, so ask 0a.5b's card and run sm install first, then this call again.
AskUserQuestion, one question, header DB type, no (Recommended) — fact-of-environment. The sample data is on the start card (1a), not here.
Name the Other-only engines in the QUESTION PROMPT so they're visibly supported — the auto-provided "Other" field can't carry its own description/examples, so the examples must live in the prompt. End the prompt with a line like:
Something else — BigQuery, SQL Server, Oracle, Databricks, Trino/Presto, DuckDB, or SQLite? Choose Other and type it (a name or a file path).
| label | description |
|---|---|
PostgreSQL | Postgres + compatible: Supabase, Neon, RDS, Aurora, Cloud SQL, Timescale, and Amazon Redshift (port 5439, SSL by default). |
MySQL | MySQL, MariaDB, RDS MySQL, PlanetScale. |
Snowflake | Snowflake. Account identifier instead of host. |
Other (Other field) | BigQuery, SQL Server, Oracle, Databricks, Trino/Presto, DuckDB, SQLite. |
Bind $DB_TYPE ∈ postgres | mysql | snowflake | bigquery | sqlserver | oracle | databricks | trino | duckdb | sqlite | dsn.
Routing:
PostgreSQL → postgres; if the user later enters port 5439 or a *.redshift.*.amazonaws.com host, transparently re-bind to redshift. A *.pooler.supabase.com host stays postgres (Supabase is hosted Postgres).MySQL/Snowflake → pass-through. BigQuery lives under Other now (or the user types it) → bigquery.Other → parse the free-form input: a DSN scheme → derive db_type (if it carries a password, follow HARD RULE 2: don't use or repeat it, ask the fields on 0a.4c instead); .db/.sqlite/.duckdb suffix or absolute file path → SQLite or DuckDB; a named DB (bigquery, sqlserver/mssql, oracle, databricks, trino/presto, duckdb) → that dialect. Only refuse with "not supported yet" for engines outside the supported set above (e.g. MongoDB, Cassandra, ClickHouse).Ask the user to name this connection — don't pick for them. The name is how they'll switch databases later (AGAMI_PROFILE=<name>) and it names the model folder (<artifacts_dir>/<name>/), so a name that means something to them — their database, product, team, or environment — beats a generic default.
On the password-page path this card comes after the connection fields (0a.4c), because the fields card asks for the database's own name and a separate "what should I call this database?" before it reads as the same question twice. Here the name is for the connection, and the database name the person just gave is the natural answer. AskUserQuestion, header Name:
"What should agami call this connection? It's how you'll pick it when you connect more than one. Type your own in Other."
Options: <database> (Recommended), the database name from 0a.4c made valid (lowercased, any other character turned into -, trimmed to 32), and <database>-<where>, with <where> = local for localhost/127.0.0.1 or the first label of the host otherwise (<database>-<account> on Snowflake, <project> alone on BigQuery, the file's stem for SQLite and DuckDB). Leave out an option that would equal the other or fail the rules below.
On the file path (no fields card), ask it here, before the file: "What should agami call this database? It's how you'll pick it when you connect more than one, so your database or product name works well. Type it in Other." with prod, staging and analytics as examples. Don't present a main default that nudges them past the choice.
Bind $PROFILE_NAME to their answer (the Other text, or a picked option). Validate: lowercase letters/digits/dashes/underscores, 1–32 chars; and not already a [section] in <artifacts_dir>/local/credentials (a profile name is a unique key — reusing one would clash). If it fails either rule, show the reason and re-ask. (The 0a.10 promote helper enforces the uniqueness backstop too — it returns COLLISION rather than overwrite — but catch it here so the user isn't surprised later. On the password-page path the helper checks again, and also refuses a name the OS store already holds a password under.) Say "database", not "profile", to the person.
Only on the password-page path (see the top of Phase 0a). Linux, and Databricks on any system, use the file in 0a.4 instead.
One AskUserQuestion, header per question, one question per non-secret field (at most 4). The password is never on this card: it goes on the page in 0a.4k. Every question takes the real value in "Other"; the options are the obvious defaults and common values, so the person presses one when it fits and types otherwise. No option is marked Recommended (these are facts about their setup). Put a line in the first question's prompt: "Type yours in Other when the options don't fit, for example your-cluster.example.com (never a password or a URL that holds one: the password goes on a separate page)."
$DB_TYPE | questions (header: options) | spec fields keys | auth |
|---|---|---|---|
| postgres / redshift | Host: localhost (this computer), 127.0.0.1 · Port: 5432 (PostgreSQL default), 5439 (Amazon Redshift), 6543 (Supabase pooler) · Database: postgres (the default database), analytics · User: readonly (a read-only user, the safest), postgres | host, port, database, user | password |
| mysql | Host: as above · Port: 3306 (MySQL default), 3307 · Database: analytics, app · User: readonly, root | same | password |
| sqlserver | Host: as above · Port: 1433 (default), 1434 · Database: master, analytics · User: readonly, sa | same | password |
| oracle | Host: as above · Port: 1521 (default), 1522 · Service: ORCLPDB1, XEPDB1 · User: readonly, system | host, port, service_name, user | password |
| snowflake | Account: acme-xy12345 (org-account form), xy12345.us-east-1 (locator form) · User: readonly, analyst · Warehouse: COMPUTE_WH (Snowflake's default), ANALYTICS_WH · Sign-in: Password (typed on a one-time page), Browser sign-in (SSO) (your company's sign-in, no password) | account, user, warehouse (+ authenticator = externalbrowser for SSO) | password, or sso for browser sign-in |
| trino | Host: as above · Port: 8080 (HTTP default), 443 (HTTPS) · User: readonly, admin · Catalog: hive, iceberg; then a second card, Password: No password, Password (HTTPS) | host, port, user, catalog | sso for no password, else password |
| bigquery | Project: acme-analytics, acme-prod · Sign-in: Google sign-in on this computer (gcloud application-default login), A service-account key file (its path in Other; the path, never the file's contents) | project (+ service_account_path) | sso |
| sqlite / duckdb | File: the absolute path in Other; options ~/data/app.db, ~/data/app.duckdb (examples) | path | sso |
Snowflake's database, schema and role, and Postgres' sslmode, are optional: ask them on a second card only when the person mentions them or the connection fails without them.
Read the answers into the spec's fields, as strings. Expand ~ to an absolute path. When an answer can't be used, say why in one line and ask that question again (an empty answer; a port that isn't a number; an example value such as acme-xy12345 or one containing example that is plainly not theirs; a value with %, or starting with # or ;, which the credentials file can't hold). A host that is a full URL with a password in it: don't use or repeat it (HARD RULE 2), and ask for the host alone.
Then run 0a.5 → 0a.8 (interpreter, agami-core, the artifacts folder, .config), and go to 0a.4k.
The password goes from the person's browser straight into the OS credential store (Keychain on macOS, Credential Manager on Windows). It is never in the chat, on a command line, in a file, or in your context: you never see it, so never ask for it, and if it is typed into the chat anyway, follow HARD RULE 2.
1. Write the spec with the Write tool to <artifacts_dir>/local/tmp/agami-connect-spec.json (non-secret fields only; there is no password key):
{"profile": "<$PROFILE_NAME>", "db_type": "<$DB_TYPE>",
"fields": {"host": "<host>", "port": "<port>", "database": "<database>", "user": "<user>"}}
For a connection with no secret to type (Snowflake browser sign-in, BigQuery, Trino with no password, SQLite, DuckDB) add "auth": "sso". The sso path has no link and no page: the helper writes the section, tests the connection, and prints only its final line, so skip step 3 and read that line in step 4. Its wait is longer than the password path's (step 2).
2. Start the helper in the background. Call Bash with run_in_background: true:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" connect_helper.py --spec "<artifacts_dir>/local/tmp/agami-connect-spec.json"
Stdout is JSON lines and nothing else. Wait for the helper's first line with the Monitor tool: the Bash result names the task and its output file, so use the Monitor tool to watch the helper's output until its first line, or the task's exit (an until-loop on that output file that stops on the first JSON line, or when the task has exited). Never run a foreground sleep: the Desktop Code tab blocks it. As a fallback where Monitor isn't available, re-read the output file at spaced intervals, each read its own tool call, never a tight loop. Stop waiting when one of these happens:
status: it is the final line. Every check that runs before the page (missing_driver, name_taken, no_store, stale_install, and the other refusals), and the whole sso path, prints that one line and exits. Skip step 3 and go to step 4 with it.url ({"url": "http://127.0.0.1:<port>/<token>/", "expires_in": 300, "pid": <n>}): the page is listening, usually within a second. Go to step 3.Next step: Try again (step 2 again) / Use a file instead (manual) (0a.4).With "auth": "sso" (auth: sso) there is no 15-second limit. The helper tests the connection before it prints anything, and that test can open a browser sign-in (Snowflake's SSO, say) that waits for the person. So tell the person once, when you start the helper, that a browser sign-in may open and that you are waiting for it to finish, then wait until the helper exits, up to 5 minutes, with the same Monitor watch. Don't repeat the line while waiting. Past 5 minutes with no exit, stop the task (below) and ask the Next step card above.
Don't run the helper in the foreground: it would hold the turn until the page is submitted, and the link would never reach the person. Where background commands aren't available, use the file path (0a.4) instead.
3. Post the link as a clickable markdown link, with this sentence and how long it lasts:
Enter your password. Enter the password on this page; it goes to your keychain, not the chat. The link expires after 5 minutes.
(On Windows say "Windows Credential Manager" in place of "your keychain".) Then a card, so the link isn't missed (a line of chat is easy to scroll past; a live run showed exactly that). AskUserQuestion, one question, header Password: "Enter the password on the page at http://127.0.0.1:// (open for 5 minutes), then come back here." Options: I've saved it / New link / Use a file instead (manual).
The helper exits when the page is submitted or the 5 minutes pass, and that exit also brings you back if the card is still open: go to step 4 and don't ask the card again. Never wait silently: if the person writes before the helper is done, answer, and remind them the link is still open. If they want to stop, stop the background task with TaskStop and its task id (the helper then takes back whatever it stored), and show the database-type card again. Where TaskStop isn't available, on macOS and Linux kill <pid> with the pid from the helper's first line stops it the same way (it asks for permission; kill sends SIGTERM, and the helper takes back whatever it stored). On Windows, and without a pid (the sso path prints none), the helper is left to stop by itself when its 5 minutes are up: say so, and wait for its exit before starting it again.
4. Read the final line of the output when the helper exits, and act on it. The exit is what you wait for after the link is posted: the Monitor tool watching the task until it exits (or, as the fallback, spaced re-reads of the output file), never a foreground sleep; the background task's exit notice also brings you back. Exit code is 0 for every outcome; status (and a refusal's reason) says what happened, and detail is the one line to show the person. Each outcome gets one sentence plus the next card:
| final line | say | next |
|---|---|---|
connected | "Connected to <name>. The password is in your keychain." (or the Windows store) | Run setup_pgauth.py --all (as in 0a.10) and continue to Phase 1. |
connect_failed | detail (why it failed). Nothing was kept: the helper removed the section and the stored password. | Card Next step: Try again (the same fields, a new link; the person may have mistyped the password) / Change the connection details (0a.4c again) / Use a file instead (manual) (0a.4). |
expired | "The link expired before the page was submitted; nothing was saved." | Card Next step: New link (step 2 again, same spec) / Use a file instead (manual). |
missing_driver | detail, which names package. | Card Driver: Install <package> (with the real package names) / Not now. On the press, install into the interpreter scripts/py uses: bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" -m pip install --user <package> (unquoted: package can hold two names, duckdb pytz), then step 2 again. If pip fails, show its last line and offer Try again / Not now. Not now: stop with "Connect again when you're ready to install it." |
refused, no_store | detail (agami's keyring library isn't set up for the OS store yet). | Card Secure store: Set up secure storage / Use a file instead (manual). The first runs bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" install (it adds keyring on macOS and Windows), then step 2 again. |
refused, stale_install | detail (the agami-core this Python has is too old for the store). | Card Update: Update agami (runs bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" install, then step 2 again) / Use a file instead (manual). |
refused, name_taken or saved_password_exists | detail (the name is in use here, or the OS store already holds a password under it). | The name card (0a.3) again, then a new spec and step 2. |
refused, bad_name | detail. | The name card (0a.3) again. |
refused, bad_field | detail (a field the credentials file can't hold). | The connection fields card (0a.4c) again. |
refused, bad_spec | Nothing to the person: the spec file you wrote is unreadable. | Rewrite it (step 1) and run step 2 again, once. A second bad_spec: say connecting failed and offer Use a file instead (manual). |
refused, unreadable_credentials or linked_credentials | detail (the credentials file under <artifacts_dir>/local/ can't be parsed, or it or local/ is a link). | Card Next step: I've fixed it (step 2 again) / Stop. Never open or print the file: it can hold passwords. |
refused, unsupported_os | detail. | The file path: 0a.4, then 0a.9. |
refused, not_replaceable | detail (--replace was run for a profile that doesn't exist or doesn't keep its password in the OS store). | Connect it as a new profile: the name card (0a.3), then step 2 without --replace. |
refused, store_error or write_failed | detail (the store or the credentials file refused the write; nothing was kept). | Card Next step: Try again (step 2) / Use a file instead (manual). |
Use a file instead (manual) always means 0a.4 → 0a.9 → 0a.10, the same as Linux. A line that is not one of these, or no final line at all: show the last line of output and offer Try again / Use a file instead (manual). Delete the spec file once the helper has exited.
On connected (the connection test passed), mark the step done and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark connect=done
<artifacts_dir>/local/credentials.exampleThe file path: Linux and any system without a secure store, Databricks on every system, and whoever picks Use a file instead (manual) in 0a.4k. The person types the password into the file themselves, so it never passes through the chat.
Use the Write tool. Shared header first, then the $DB_TYPE body with [$PROFILE_NAME] as the section.
Header:
# <artifacts_dir>/local/credentials.example
# Fill in your values below and save, then press "I've filled it in" in the chat.
# agami moves this file to <artifacts_dir>/local/credentials and chmod-600s it for you — no
# manual save or chmod needed. (Don't rename it yourself.)
# agami only runs read-only SELECT queries, so a read-only database user is all it needs
# (and the safest thing to connect). Copy-paste GRANT SQL for your database:
# plugins/agami/shared/readonly-grants.md — or ask agami for "the read-only grant".
# Format reference: plugins/agami/shared/credentials-format.md
# Switch profiles with AGAMI_PROFILE=<name>.
Bodies — postgres, redshift, snowflake, mysql, bigquery, sqlite are unchanged from shared/credentials-format.md (URL-form first for Postgres/MySQL/Redshift; account fields for Snowflake; project+service_account_path for BigQuery; path for SQLite). The new dialects:
# SQL Server / Azure SQL.
[$PROFILE_NAME]
type = sqlserver
host = your-server.database.windows.net
port = 1433
database = your-database
user = your-username
password = your-password
# Oracle.
[$PROFILE_NAME]
type = oracle
host = your-host.example.com
port = 1521
service_name = ORCLPDB1
user = your-username
password = your-password
# OR a full DSN: dsn = host:1521/ORCLPDB1
# Databricks SQL warehouse.
[$PROFILE_NAME]
type = databricks
host = your-workspace.cloud.databricks.com
http_path = /sql/1.0/warehouses/abc123
token = dapiXXXXXXXXXXXX
# catalog = main # optional Unity Catalog
# Trino / Presto.
[$PROFILE_NAME]
type = trino
host = your-coordinator.example.com
port = 8080
user = your-username
catalog = your_catalog
schema = your_schema
# password = ... # uncomment for HTTPS + basic auth
# DuckDB (local file or in-memory).
[$PROFILE_NAME]
type = duckdb
path = /absolute/path/to/your.duckdb
Always finish with the additional-profiles hint (one commented block):
# Add more profiles by appending another [section]. Switch with AGAMI_PROFILE=<name>.
# [staging]
# type = postgres
# url = postgresql://readonly:[email protected]:5432/mydb
For BigQuery / Databricks / any key-or-token file: remind the user to chmod 600 it.
<python3> = data.interpreter.python3, written out in full, from the Phase-0 connect_resolve.py call — the ONE Python agami uses for the model and DB connections (introspection always runs python -m execute_sql under it on every tier, so the DB driver must live in it). It's already the scored pick — the candidate that has pydantic+sqlglot+pyyaml AND the $DB_TYPE driver — so there's no guessing and the user sets nothing. Re-run bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" connect_resolve.py --db-type <db_type> now that the DB type is known, so the interpreter is scored against the right driver and native tools are refreshed. It records as tool_paths.python3 in 0a.7. (AGAMI_PYTHON is honored as a first-priority override but is never required.)
Native CLIs (optional fast path for queries — introspection doesn't use them) are in data.tools (psql/mysql/snowsql/sqlite3/duckdb/bq, null if absent), detected with which only. Forbidden elsewhere: pgrep/ps/lsof/find //ls /Applications/port scans.
If data.interpreter.has_driver is false the $DB_TYPE driver isn't in <python3> yet — confirm via AskUserQuestion, then "<python3>" -m pip install --user <package> from the table, where <python3> is data.interpreter.python3 written out in full (probe was already done in <python3> by connect_resolve.py):
$DB_TYPE | probe ("<python3>" -c '…') | pip package |
|---|---|---|
| postgres / redshift | import psycopg2 | psycopg2-binary |
| mysql | import pymysql | pymysql |
| snowflake | import snowflake.connector | snowflake-connector-python |
| bigquery | import google.cloud.bigquery | google-cloud-bigquery |
| sqlserver | import pymssql | pymssql |
| oracle | import oracledb | oracledb |
| databricks | from databricks import sql | databricks-sql-connector |
| trino | import trino | trino |
| duckdb | import duckdb, pytz | duckdb pytz |
| sqlite | stdlib — always present | — |
duckdb needs
pytzto materializeTIMESTAMP WITH TIME ZONEvalues into Python — without it a query that selects a timestamptz column fails at runtime (Required module 'pytz' failed to import), so it's part of the driver install, not optional.
If the driver is missing, confirm via AskUserQuestion, then "<python3>" -m pip install --user <package> (plain pip install fallback). Same "never install silently" convention as the model deps (0a.5b). Do this for <python3> so sm introspect connects on the first try.
This runs first, right after 0a.0: saving the folder (0a.6), setting it up (0a.1) and writing .config (0a.7) need agami's library, and none of them installs it (each stops with exit code 12 and the install step instead), so the person agrees to the install before anything is set up. The model (introspection, validation, traversal, curation — everything the sm wrapper drives) needs pydantic + sqlglot + pyyaml in the interpreter agami uses. The resolve step already checked the interpreter it picked: data.interpreter.core_ready in its output (preflight step 1) says whether agami's library is ready in it (the deps, the agami-core package itself and this plugin's version), so no command is needed here. Decide on core_ready, never on has_model_deps alone: the deps can be there with no agami-core, and then every setup call stops with exit code 12.
If it is ready, continue. If missing, confirm via AskUserQuestion before installing (same convention as the DB-driver install above — agami never installs silently):
agami needs the agami-core package (which pulls
pydantic,sqlglot,pyyaml) to build and read the semantic model. Install it now? (one-time, user-site —pip install --user)
On Yes: bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" install — the sm launcher is the single place that installs the agami-core library into the resolved interpreter (editable from a dev checkout, else the published package via PyPI or pinned git — so it works in a marketplace install with no packages/ dir), and everything (python -m execute_sql / python -m semantic_model.cli / sm) then resolves it. On No: stop with "Can't build the model without it — re-run when you're ready to install." — don't proceed to introspect.
(The sm wrapper also self-installs these on first use as a safety net, but doing it here makes it explicit, confirmed, and at a predictable moment rather than mid-introspection.)
<artifacts_dir> (first run only)This runs before 0a.1, because 0a.1 and 0a.7 act only on the folder agami has saved. The folder is chosen once, on the very first onboarding, and reused for every profile thereafter. Whether it is already set is in the resolve step's output (preflight step 1): when data.artifacts_dir_source is env (AGAMI_ARTIFACTS_DIR) or pointer (the saved pointer), or data.config.present is true, skip this question entirely — reuse data.artifacts_dir and continue to 0a.1. Never read or list the pointer file yourself. Only a brand-new install (artifacts_dir_source is default and no .config) reaches the question below. This guarantees a second/third database lands as a sibling inside the same folder rather than re-prompting (and risking a fragmented, multi-folder setup).
The options follow the operating system the session's environment names (as at the top of Phase 0a). Then AskUserQuestion with the two defaults for that OS as named options (Recommended first). The auto-provided Other lets the user type any absolute path — so this both gives sensible options and allows a full custom path:
Where should agami save your semantic model, examples, and preferences? This is the parent for ALL profiles — each lands in
<artifacts_dir>/<profile>/. It's non-secret (no credentials) — point it inside a git repo to share the tuned model with your team. Credentials stay in<artifacts_dir>/local/regardless.
| OS | Option 1 — Recommended | Option 2 |
|---|---|---|
| macOS | ~/agami-artifacts | ~/Documents/agami-artifacts |
| Linux | ~/agami-artifacts | ~/Documents/agami-artifacts |
| Windows | %USERPROFILE%\agami-artifacts | %USERPROFILE%\Documents\agami-artifacts |
(For Other, suggest a team repo path as the example, e.g. ~/code/acme-data/agami.) Expand ~ / %USERPROFILE% to an absolute path, then save the choice, whichever option it is, with one call (it checks the folder is absolute, not a file and not inside <artifacts_dir>/local/, and writes the pointer at <home>/.config/agami/path so future sessions find it; never write the pointer yourself):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" choose-folder "<artifacts_dir>"
An error is said back and the same card asked again. Then 0a.1; 0a.7 records the folder in .config.
<artifacts_dir>/local/.configOne call, which checks each value and keeps every other key in the file (written 0600):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" set-config "<artifacts_dir>" --tier <tier> --active-profile <profile> --python3 "<python3>" --tool <tool>="<tool_path>"
<tier> is cli, duckdb or python; --tool names the native query tool the tier uses (psql, mysql, snowsql, sqlite3 or duckdb) with its absolute path, left out for the python tier. python3 MUST be the <python3> resolved in 0a.5 (the interpreter that has both the model deps and the DB driver) — sm and the introspection engine read it from here, so recording the wrong one reintroduces the interpreter mismatch. Never write .config with the Write tool.
The database's folder is known from here, <root> = <artifacts_dir>/<profile>: mark the step started and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark connect=in_progress
<artifacts_dir>/USER_MEMORY.md if missingWrite the default seed (per shared/user-memory-format.md) with the Write tool, which makes the folder; the file comes out readable by others under the usual umask, as this non-secret file should, so it needs no chmod. Don't overwrite. Migrate a v1.1 <artifacts_dir>/local/USER_MEMORY.md if present.
Then write what 0a.0 held (the folder and the interpreter exist now): the company (1.4 A's two writes) and, when it was given, the personal-data setting (sm set-personal-data). The fiscal year waits for 1.7.
Show the summary; it ends the turn with the reply line below (a summary before a card in the same message does not reach the person, long-text.md).
✓ <artifacts_dir>/local/ ready (chmod 700)
✓ Credentials template → <artifacts_dir>/local/credentials.example
✓ Tool detected: <tool> (<tier>)
✓ Artifacts dir: <resolved path>
Open <artifacts_dir>/local/credentials.example, fill in your connection details and save it
(keep the filename as-is — don't rename it). I'll secure the file and run the full
introspect → enrich → seed flow.
Tip: agami only runs read-only queries, so a read-only database user is all it needs
(and safest). Want the exact GRANT SQL for your database? Just ask.
The reply line: Reply "I've filled it in" once the file is saved, or "show me the file again". Handle the reply as the choices below; words that mean one of them count as it:
| label | description | then |
|---|---|---|
I've filled it in | Secure the file and connect | 0a.10 |
Show me the file again | Where the file is and what to fill in | Print the path and the field names of the [$PROFILE_NAME] section from the template you wrote (from your own copy, never by reading the file: once filled in it holds the password), then the reply line again. |
The reply is the wait: don't continue to Phase 1 until I've filled it in is said (or, in a later session, until the person comes back with any data question and preflight returns promote).
Show the read-only Tip line only for dialects with a user/role concept (postgres,
redshift, mysql, snowflake, sqlserver, oracle, databricks, trino); omit it for
sqlite / duckdb (file-based, no user) and when BigQuery auth is ADC. If the user asks for the
grant, read shared/readonly-grants.md, pick the $DB_TYPE
block, and fill in whatever <…> placeholders it uses (e.g. <db> / <schema> / <warehouse> /
<catalog> / <project> / <dataset>) from the values they entered.
The person said I've filled it in to the 0a.9 reply line (or came back later with a data question, and preflight returned promote). Promote it deterministically with the helper — do NOT hand-roll an mv/append, and do NOT assume "no file yet." The script handles all four cases (first profile → move; Nth profile → append; name clash → refuse; placeholders → refuse), so the second-profile and [main]/[main] cases can't silently corrupt the file:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" promote_credentials.py
Read the first token of stdout and act:
SECURED <profile> → credentials created from the template (chmod 600, .example consumed). Continue.APPENDED <profile> → the new profile was appended to an existing credentials file (other profiles untouched, chmod 600). Continue.COLLISION <profile> → a profile by that name already exists; nothing was changed. Tell the user "You already have a profile named <profile> — pick a different name for this database," go back to 0a.3 to rename, re-write the template in 0a.4 under the new name, and say the 0a.9 reply line again. Never overwrite or duplicate an existing profile.PLACEHOLDERS_REMAIN <fields> → the template still holds template values; tell the person which fields to fill and say the 0a.9 reply line again (never introspect against a template).NOTHING → no credentials.example to promote (already promoted, or never written) — fall back to the preflight decision.(${CLAUDE_PLUGIN_ROOT} is the plugin root, filled in with its absolute path when this skill loads; promote_credentials.py is stdlib-only and needs no special interpreter.)
Run setup_pgauth.py --all before the first native-CLI query (writes .pgpass / .mysql.cnf so passwords never hit the command line). Idempotent. Then continue to Phase 1.
Before Phase 1, with the connection saved (this path doesn't test it; Phase 1's first read does), mark the step done and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark connect=done
Runs only when the person chose Try the sample data on the start card (Phase 0, step 1a) (or said "I don't have a database" / "try the sample" / ran agami-connect sample). This replaces Phases 0a, 1, and 2 with a short deterministic wire-up — no credential template, no hand-off turn, no live introspection on the fast path. The committed sample dataset + its prebuilt model live at ${CLAUDE_PLUGIN_ROOT}/samples/store/ (seed.sql, build_sample.py, model/). Profile is always agami-example.
If <artifacts_dir>/agami-example/datasource.yaml already exists, the sample is already set up → skip to the demo query (step 7), or treat reintrospect as the 6B rebuild.
The task list is the onboarding steps from sm steps, as on every path (shared/task-list.md); here <root> is <artifacts_dir>/agami-example.
Resolve the environment first, since the short-circuit skipped preflight step 1: bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" connect_resolve.py --db-type sqlite --profile agami-example. Its output names everything this path uses: data.artifacts_dir is <artifacts_dir> (on a first run, when data.artifacts_dir_source is default and there is no .config, ask 0a.6's card instead, default ~/agami-artifacts, and save the answer with its sm choose-folder call before init-local below), data.interpreter.python3 is <python3>, data.interpreter.core_ready says whether agami-core is installed and current in it, and data.tools.sqlite3 says whether the sqlite3 CLI is there.
The agami-core package first (trimmed 0a.5/0a.5b), because setting up local/ needs it and never installs it: SQLite needs no DB driver (stdlib), so only ensure the agami-core package is importable in <python3>. When core_ready is false, confirm via AskUserQuestion, then bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" install (the one, one-time install via the sm launcher; brings pydantic/sqlglot/pyyaml and works with no packages/ dir).
Then set up local/ (same as 0a.1), one call: bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" init-local "<artifacts_dir>".
Mark the step started and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark connect=in_progress
The tier: tier is cli when step 1's data.tools.sqlite3 is a path, else python; no which call. (agami-core was installed in step 1, before local/ was set up.)
Build the .db into the gitignored local/ (it's regenerable machine state, not committed):
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" "${CLAUDE_PLUGIN_ROOT}/samples/store/build_sample.py" --out "<artifacts_dir>/local/samples/store.db"
Uses the sqlite3 CLI if present, else the stdlib builder; prints the size.
Write the [agami-example] credential with the deterministic promoter — don't hand-roll the INI, and don't write the file yourself. --sample writes local/credentials.example with the sample's section (its path the database from step 3), never over an existing one; then promote it:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" init-local "<artifacts_dir>" --sample
bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" promote_credentials.py
SECURED/APPENDED → chmod 600, collision-safe. (No placeholders → never trips PLACEHOLDERS_REMAIN.) An error from init-local --sample means credentials.example is another connection's template, left from an earlier attempt: don't run the promoter. Say the error in plain words, and ask a card, header Template: Finish that connection (0a.9) / Stop here (the person moves the file, then tries the sample again).
Write <artifacts_dir>/local/.config (as 0a.7 does), one call; add --tool sqlite3="<sqlite3_path>" when step 1 found the sqlite3 CLI (tier cli), else leave it out (tier python):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" set-config "<artifacts_dir>" --tier <tier> --active-profile agami-example --python3 "<python3>"
The sample database is ready: mark the step done and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark connect=done
Fork — copy the ready-made model, or rebuild it live? (AskUserQuestion). Ask once, before touching <artifacts_dir>/agami-example/:
The sample comes with a ready-made semantic model. Want to query it right away, or watch agami build that model from the data first?
| option | branch |
|---|---|
Just let me query it (Recommended) | 6A — copy |
Build the model from scratch so I can see it work | 6B — rebuild live |
cp -R "${CLAUDE_PLUGIN_ROOT}/samples/store/model/." "<artifacts_dir>/agami-example/", one call (step 1's connect mark already made the folder). Validate it loads here: bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" validate "<artifacts_dir>/agami-example". If it fails, surface the errors and stop — never leave a half-wired profile. Then mint the deployment org_id (a copy carries no id — introspect mints inline, a copy bypasses it): bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" ensure-org-id "<artifacts_dir>/agami-example" — idempotent, writes a locally-minted uuid into datasource.yaml so the sample deployment has a portable identity like any other. Then stamp a model_version (a copy doesn't go through introspect/curate, so nothing auto-stamps it): bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" snapshot "<artifacts_dir>/agami-example" — best-effort, so the answer receipt shows a version rather than null. (We stamp at copy time instead of committing a static .snapshots/ so it always matches the model's actual content; 6B gets one automatically from introspect.) Then mark the build done, so a resumed sample session shows the right current step: bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark build=done, and do what its then says (shared/task-list.md).model/ and run the normal Phases 1→2 against the agami-example profile (--db-type sqlite) — the same introspect → enrich → seed pipeline a real onboarding uses, just pointed at the sample SQLite file. It is the non-default option. Don't mention tokens, cost, billing or a duration: report progress from the engine's counts as it goes.
then says:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" progress "<root>" --wait 20
The build of the sample file takes a minute or more (it tests possible joins against the data), so never say it takes seconds.unreviewed, so seed-examples would refuse with preseed_review_pending. Because the sample is curated and trusted, auto-approve the queue as a system signer right before seeding — the silent path clears its own gate:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" approve-queue "<artifacts_dir>/agami-example" --signer system --role system
(This is only sanctioned for the curated sample; a real database keeps the human sign-off gate.)/agami-model posts (its Phase 1: read the model with sm model-tree and sm review-items, never the YAML): one sentence on what needs sign-off (after the system approval above, usually nothing) and the Subject area | Tables | Hidden table. This is the whole point of "watch it build"; a wrap with no numbers would defeat it. Post it together with step 7's short dataset description + starter questions (so don't cede the turn). No page opens: the model explorer is the full view, rendered and served from localhost by /agami-model only when the person asks for it. (Do not render the NL→SQL examples-validation page either.)6A → step 7 (describe + stop). 6B → the model overview above, then step 7's description + starter questions. Both end with a validated <artifacts_dir>/agami-example/ model.
Wrap up — describe the dataset, offer questions, then STOP. Do NOT auto-run a query. First mark the last step started (on 6A right after the copy, on 6B once the model validates, and when the sample was already set up), and do what its then says (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark first_question=in_progress
The step stays in progress until the first question is answered: agami-query marks it done then (its Phase 4f), never this step. This is the entire closing for the sample path: skip the rest of Phases 3–8 (no introspect summary, no "re-introspect <profile>" / "when you want the real thing" framing — that pushes the user off the sample they just picked and can surface another profile's name). The user asked to query the sample, not watch a scripted demo — so hand them the keys, don't drive. (6B adds the model overview in the chat, see 6B. Neither path opens a page.)
Short description (2–3 lines, plain): what the dataset is, drawn from <artifacts_dir>/agami-example/datasource.md — Acme Store, a retailer with one-time commerce (customers, products by category, orders, line items, payments, refunds) and recurring subscriptions (plans, subscriptions, invoices). ~500 customers, ~4,000 orders over ~2 years. State it; don't sell it.
A card of starter questions — and DO NOT answer any until one is picked. AskUserQuestion, one question, header Ask, "What would you like to ask? Pick one or type your own in Other.", no (Recommended). Four options, at least two of them multi-table joins so the person sees agami handle real joins, not just single-table counts, each with the tables it joins as its description:
| label | description |
|---|---|
Revenue by product category | Line items joined to products and categories |
Top categories per channel | Which categories drive the most revenue in each sales channel |
Top 5 customers by spend | Orders joined to customers |
Active subscriptions and MRR | Subscriptions joined to plans |
(The first two are the multi-table joins. All four are backed by EXPLAIN-validated seed examples in the shipped model, so they answer reliably. "Other" takes any question, a monthly trend or "customers with both an order and a subscription" among them.) Where AskUserQuestion is unavailable, list the same four as a numbered list (question-cards rule 7).
Then stop and wait. Nothing about agami-serve / agami-model / corrections yet — let them experience one real query in Claude Code first. When the user picks a question or asks anything, hand to agami-query — it answers AND runs its own first-query flow (the one-time GitHub-star ask + /agami-serve pointer, gated by local/.optins). Do NOT pre-narrate fan/chasm traps or "what agami caught." If their question hits a trap (questions 1–3 can), agami-query surfaces it in the answer's receipt — let it happen on a real question instead of scripting it.
The "where to go deeper" footer (corrections / /agami-model / /agami-serve) fires from agami-query, not here. When the user asks their first sample question, agami-query owns the turn — so its Phase 4f surfaces a one-time orientation footer for the agami-example profile (see agami-query SKILL.md → Phase 4f). Don't try to print it from Phase 0s — a footer placed here never executes once agami-query has taken over. Phase 0s ends at step 7 (describe + questions + stop).
Mark the step started and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark context=in_progress
Tell the user before the first probe what the build does, never how long it will take: no time estimate in any form, because how long it takes depends on the network, the warehouse and the data, and a guess is wrong by ten times as often as it is right. Say the steps instead: "I'll read each table's columns and keys, check every join against the data, and profile what the columns hold." When a step is slow for a known reason, say the reason ("each statement goes over the network to the warehouse"), not a duration.
Then report progress from the engine's real counts as it goes (in the background, with sm progress --wait, per 1.7):
columns+grain 30/52, joins: checking 78 on the data, joins checked 140/300, profiled 20/42 tables.
Each log line starts with its UTC time (2026-11-17T10:04:00Z columns+grain 30/52); quote the message
after it. Quote the counts the progress log printed; never estimate, round up or extrapolate one. For
reintrospect, say it reads every table again.
Open the progress page when the build will take more than a few minutes — 15 or more tables on a
database reached over the network, or any batched build (1.7, where background commands aren't available). Builds read up to 4 tables at
once, but only one at a time when the profile's sign-in may prompt (any Snowflake authenticator
other than a password, key pair or token). Start it in the background
(run_in_background) before the first introspect call, wait for its one line (the Monitor tool, never
a foreground sleep); its url is <progress_url>:
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" progress_page.py "<root>/.introspect/progress.log" --minutes 240
It prints {"url": "http://127.0.0.1:<port>/<token>/", "expires_in": 14400}; open that URL with bash "${CLAUDE_PLUGIN_ROOT}/scripts/open_in_browser" "<progress_url>", its own call.
"Build progress shows each stage, its count and how long it has run." The page reads the
log every few seconds: batch n of N, tables read of total, the stages still to come by name, the
current stage's count, the time elapsed, and "Waiting on the database for 12 min: checking joins of
orders" when the log has gone quiet. It never estimates the time left. Keep posting one line in
the chat per stage change as well (the page may not open in a remote or web session): Reading columns and keys, Finding relationships, Checking joins on the data, Profiling columns,
Testing join candidates, done. When the log says waiting on the database for <N> min: <what>,
pass that on in one line: it means a statement is slow, not that the build has stopped. Stop the
page (TaskStop) when Phase 1 is done.
If <artifacts_dir>/<profile>/datasource.yaml exists and $ARGUMENTS != reintrospect: the profile is already onboarded. When the start card (Phase 0, step 1a) already took the person's choice, act on it and skip this menu. Otherwise offer (AskUserQuestion, no (Recommended) — these are equal-weight choices), capped at 4:
<profile> — refresh the structure from the live DB (new/changed tables, columns, FKs) while preserving descriptions, entities, metrics, caveats, and sign-offs (the reintrospect path; 2e: preview, then write)./agami-model; its explorer page is the full view, only when asked).<profile> untouched. On this choice, first ask whether it's the same company or a different one (see 1.1a), then start a fresh onboarding: jump to the profile-naming step (Phase 0a's naming question) → have the user name the new profile (must differ from <profile> and any existing [section] in <artifacts_dir>/local/credentials) and pick its DB type → write that profile's credentials.example → run the full flow for it. Never reuse or overwrite the current profile's credentials or model.agami-example sample (retail + subscriptions, no connection needed), leaving <profile> untouched. Routes to Phase 0s. This MUST be a real selectable option here (not a prose aside) — a returning user with an onboarded profile has no other visible path to the sample, since plain /agami-connect resolves their active profile and lands on this menu.(Cancel isn't a listed option — the modal's Esc / "Other" covers "do nothing"; the four real choices are the actions above. Keep the list at exactly these four.)
Same DB, another schema? That's the Re-introspect path, not "Onboard another database." If the user wants to add a schema that lives in the same database they already onboarded (e.g. they did public, now they want billing too), choose Re-introspect and expand the schema selection in Phase 1.3 to include both the old and the new schemas. The engine scans them together in one pass, so any relationship between the original and the new schema is detected as a first-class cross-schema join (Case 1) and surfaced for review. Picking "Onboard another database" instead would split the two schemas into separate models and demote any link between them to manual cross-profile glue (Phase 2b federation) — wrong for one DB. If you're unsure which the user means, ask: "Is billing in the same database connection as <profile>, or a different server/database?" — same connection → Re-introspect + expand schemas; different → new profile.
The engine auto-backs-up any legacy (v1) model (index.yaml + per-schema _schema.yaml) it finds at the profile root into .legacy_backup/ before writing — so a first run over an old profile is safe and reversible; surface a one-liner when that happens.
When the user chooses Onboard another database, ask (AskUserQuestion, header Same org) whether the new database belongs to the same company or a different one. A deployment (one artifacts dir) holds exactly one company/organization with many datasources under it; a genuinely different company is a different folder.
<artifacts_dir>, shares the same org_id from the root organization.yaml, and shares the company context authored earlier. Do not re-ask the company description (1.4 detects the already-authored company context and skips it); the per-database note is still asked. Narrate it: "This attaches under your <company name> organization, sharing the company context you set earlier — its per-database notes stay its own."bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" choose-folder "<new_artifacts_dir>"; then one call makes the folder, its private local/ and the .gitignore line, bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" init-local "<new_artifacts_dir>".
When the resolve step's data.artifacts_dir_source is env, the person set AGAMI_ARTIFACTS_DIR, which outranks the saved folder, and no call of yours can change it for the calls after it; choose-folder refuses and its error says what to do. Don't run those calls: say in plain words that the folder is set in their environment, that they change AGAMI_ARTIFACTS_DIR to the new folder (or remove it) where they set it, restart Claude Code and connect again, and stop there.
The current org's files are untouched; the first onboarding in the new folder mints a fresh org_id + its own company record (1.4 authors it there). This is the only way to run two companies from one machine — one folder each.Run cli areas/probe is not needed yet — schema discovery happens inside the engine. But decide scope first:
Catalog reachable (common): after the engine lists schemas, it introspects all of them. If the DB has many schemas (Snowflake with 50+), 1.6's summary shows them with their table counts and its Only some schemas answer narrows them; there is no separate schema question on a first onboard.
auth, storage, vault, realtime, extensions, …) so only the user's app schemas (e.g. public) are modeled (it surfaces a note saying which it skipped). Don't hand-build a --tables allowlist for Supabase to dodge the system tables — that's already done, and a manual allowlist is fragile (shell word-splitting, missed tables). Only allowlist when the user genuinely wants a subset of their own tables.Catalog denied (locked-down role): if a quick probe shows the catalog isn't readable, the engine cannot enumerate tables, so ask for them on a card. Say first, in one line: "Your role can read the data but not the catalog, so I can't list the tables myself; I'll describe each one from the data." Then call AskUserQuestion, one question, header Tables, "Which tables should I model? Type them in Other, e.g. sales.orders, sales.customers.":
schema.table or a bare table name.shared/readonly-grants.md in a fenced block, for the person to give their admin, then this card again.Write the names, one per line, with the Write tool to <artifacts_dir>/local/tmp/agami-names.txt. Where an inventory exists (a re-introspect, or a discover pass that listed some tables), check them first with AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" inventory_summary.py --inventory "<inventory_path>" --keep names:<artifacts_dir>/local/tmp/agami-names.txt --tables-out "<artifacts_dir>/local/tmp/agami-keep.txt": an unmatched or ambiguous name is said back and the same card asked again, never guessed. With no inventory to check against, pass the file as it is. Then run the engine with --tables-file on that file (never an unquoted --tables list). Everything the engine then infers (types, grain, FKs) lands unreviewed for sign-off.
On a first onboard, skip this step. 1.6's summary shows every schema with its table count, and its Only some schemas answer narrows them, so a schema question here would ask the same thing twice.
On re-introspect / an existing model, ask which schemas to rescan, and make "add" vs "replace" explicit. Read the schemas already in <profile>'s model (the distinct schema of its existing tables). Call AskUserQuestion, one multiSelect question, header Schemas, "Which schemas should I rescan?", with at most 4 options:
groups.schema_groups does in 1.6), one option per group naming its schema count, at most 2 such options."Other" takes schema names to add, or drop <schema> to take one out. Record selected_schemas as the union of what was picked; the engine scopes to these. Tell the user plainly:
The engine re-scans exactly the schemas you check here and rebuilds the structure from them. To add a schema, leave the existing ones checked and tick the new one — relationships between them get found in the same pass. Unchecking a schema removes its tables from the model (its hand-edits are preserved only if you keep it checked).
This is the union-rescan that makes Case 2 work: adding billing to a model that already has public must scan public ∪ billing together — scanning only billing would build the new schema's internal joins but miss every join back to public (a cross-schema edge needs both endpoints in one introspection pass). Never silently re-scan just the delta.
Reconcile what you'll scan vs what's actually there — NEVER silently shrink the scope. When the user picks All schemas (or you narrow the set yourself), do NOT quietly hand the engine a smaller list. Count what the catalog holds (schemas + tables) and state plainly what you're INCLUDING and what you're LEAVING OUT, with a reason for each exclusion, then confirm. Three kinds get excluded and each must be named, not dropped silently:
pg_auto_copy, pg_*, information_schema, Supabase auth/storage/… (the engine already drops these; still report them).public full of Salesforce objects (accounts, opportunities, leads, contacts, pricebooks) sitting next to ServiceNow module schemas. Don't fold a foreign domain into this model; name it and offer it as its own profile.--tables/--tables-file subset.Example to say BEFORE introspecting: "Found 70 tables across 18 schemas. I'll model the 52 in the 16 ServiceNow module schemas. Excluding: public (17 — accounts/opportunities/leads… looks like a separate Salesforce dataset; onboard it as its own profile if you want it) and pg_auto_copy (1 — Redshift system). Good?" A user who said "all" must SEE the delta up front — never discover later that 19 tables never made it in. This is mandatory whenever discovered-count ≠ scanned-count.
Four cards, asked right after the connection works and before tables are listed: the company (once per deployment; already asked in 0a.0 on the usual path), what the person can share (1.5), this database's one line, and when its fiscal year starts (skipped when 0a.0 already gave it). They are required state-gathering: "don't ask clarifying questions" does NOT cancel them, and the skill never decides skip for the person. Conventions: shared/question-cards.md. The sample path skips all four (its model is ready-made).
A. Company card — ONCE, on the first onboard into this deployment. Normally already asked in 0a.0, at the very start; don't ask it twice in one run. Decide "already authored" by content, not by file existence: done only if the root <artifacts_dir>/organization.md exists or <artifacts_dir>/organization.yaml has a non-empty name/description. Otherwise AskUserQuestion, one question, header Company:
"What's your company called, and what does it do? Type a sentence or two in Other, name first. It's shared by every database you connect here."
Options: Skip for now (no company context; say it can be added later in /agami-model) and Draft it from the database (after the build, Phase 2f drafts a short description from the model and Phase 7 shows it as a draft to correct). Text in "Other" is the answer. Write it as both of these (the record write is the only thing that fills organization.yaml):
<artifacts_dir>/local/tmp/agami-org-name.txt and <artifacts_dir>/local/tmp/agami-org-description.txt, then bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" set-org "<artifacts_dir>" --name-file "<artifacts_dir>/local/tmp/agami-org-name.txt" --description-file "<artifacts_dir>/local/tmp/agami-org-description.txt". The person's text never goes on the command line, where the shell would read a quote or $ in it.<artifacts_dir>/organization.md under # About this company (narrative prose ONLY — no model facts).Then confirm both landed. On a later onboard (company context already there) don't ask: say "Sharing the <company> context you set earlier."
B. Context card — every onboard. This is 1.5 below; ask it after A.
C. About-it card — every onboard. The one line list_datasources shows an agent so it can pick the right datasource (an organization with several refuses a query that names none), and, when the person writes more, this database's narrative. AskUserQuestion, one question, header About it:
"In one line, what does this database hold, and when would someone query it? Type it in Other, e.g. "Invoices, payments and products: use for revenue questions." Add more sentences if a term means something specific here."
Options: Generate one for me (Recommended) / Skip.
Nothing is written at this step — datasource.yaml does not exist until introspection (1.7) creates it. Bind the answer and act on it after 1.7:
$DATASOURCE_DESCRIPTION, written right after 1.7: the sentence, exactly as the person wrote it, with the Write tool to <artifacts_dir>/local/tmp/agami-description.txt, then bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" set-description "<root>" --description-file "<artifacts_dir>/local/tmp/agami-description.txt". The person's text never goes on the command line. When it has more than one sentence, the whole text also goes to <artifacts_dir>/<profile>/datasource.md under # About this database.$DATASOURCE_DESCRIPTION = generate. Phase 2f writes it once every table is enriched, and the Phase 7 summary shows it as a draft they can edit.model_deploy will warn about it, and that an agent picking between several datasources will be guessing from the name.If datasource.yaml already has a non-empty description (a re-onboard), show it and ask Keep it (Recommended) / Replace it instead. Keep it → $DATASOURCE_DESCRIPTION = keep; nothing is written. Replace it → ask the card above and bind from that answer. Without a narrative from this card, Phase 2f writes a short per-database starter from the enriched model.
D. Fiscal-year card — every onboard, unless datasource.yaml already has fiscal_year_start_confirmed: true or 0a.0's Source answer gave the month ($FISCAL_START_MONTH, written after 1.7 the same way). The build never writes a fiscal start, January included: a January written by default was once never questioned for an organisation whose year starts in another month. AskUserQuestion, one question, header Fiscal year:
"Which month does your fiscal year start in? Type another month in Other."
Options: January (the calendar year) / April / July; no option is Recommended, and "Other" takes any month. Bind the month (1 to 12) and write it right after 1.7: bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" set-fiscal-year "<root>" --month <month>. January is written like any other month: that is what records it as asked. Never write one the person didn't give; a skipped card leaves it unset, and 2g asks it again.
These are non-secret model files and must stay readable (e.g. by the deploy container / a teammate reading a checked-in copy): the Write tool leaves them readable under the usual umask, so no chmod is needed; never chmod 600 them (that's for local/ secrets only). See shared/organization-context-format.md for the content-routing rule (company-wide → root; per-database → the profile; per-column units → the structured model; personal → USER_MEMORY.md).
The context card (1.4 B). Same "required state-gathering" rule. AskUserQuestion, one question, header Context, multiSelect:
"What can you share so answers match how your team works? Pick any that you have."
| label | description | then |
|---|---|---|
Ask me as you go (Recommended) | I'll answer what the data can't settle. Picked alone: build from the database and ask only that | Nothing now. After the descriptions, 2g asks on cards only what the data itself can't answer. |
Definitions or a semantic layer | A data dictionary, metrics list, ERD, spec workbook, or a dbt / LookML / Cube repo | A follow-up card: "Type the file or folder path in Other, or attach the file to your next message.", options Skip this one / I'll attach it (wait for the attachment). Then read it as the sections below say: a doc, a column dictionary, a model spec workbook, or a semantic-layer repo by what the path holds. |
Questions people ask | Real questions from your team; they become checked examples, and the measure of how right the model is | A follow-up card: "Type them in Other, one per line, or a file path.", options Skip this one / I'll attach a file. Save them with the Write tool to <artifacts_dir>/local/tmp/agami-asked-questions.txt, one per line; Phase 5 writes SQL for each and checks them with the rest. |
Report SQL or dashboards | SQL you trust, an export, or a screenshot; checked against the model after the build | A follow-up card: "Type a path to a .sql or .csv file in Other, or attach a screenshot to your next message.", options Skip this one / I'll attach it. Copy files or pasted SQL into <artifacts_dir>/local/reconcile/inbox/ (SQL as <ts>.sql, a CSV as is; note a screenshot's path). Phase 6b hands them to /agami-reconcile. |
Ask me as you go comes first because most people have no document to hand over, and a model built from the database alone guesses wherever the data has two readings: knowledge is asked for where the data shows a gap, not handed over up front. It goes with any of the others, and picked alone it is also the card's "nothing to hand over" answer, so the card can always be submitted. A person who wants neither documents nor questions types it in "Other" ("nothing", "don't ask me"): build from the database alone and leave 2g out.
This card is where the things 0a.0 listed are handed over. Don't ask the source system again: when 0a.0's Source card named a product, the published-product-schema path below is already on.
"Other" on the context card takes a named product ("it's ServiceNow", "this is our Salesforce") → the published-product-schema path below; or any of the above typed straight in (a path, questions, SQL), routed by what it is. A question about the options ("what's a semantic layer?") is answered first and the card asked again (question-cards rule 5a).
Ask the follow-up cards one at a time, in the table's order. Nothing here is required: every follow-up's Skip this one goes on to the next.
A model spec workbook is recognised by its sheets, whatever the user called it: an .xlsx with Subject areas, Tables and Joins sheets is one, attached under the first option like any doc. Take the model-spec path for it — never Read it as a doc: the parser reads every row, and a doc read is trimmed and paraphrased.
If a doc: Read the path (handles PDF/image/md/text/CSV natively; trim huge files to first 20 pages / 50 rows). Any other .xlsx/.docx → ask for PDF, proceed without if not.
A column data dictionary is not read as a doc. A CSV or JSON with one row per column (table, column, description, optionally area / schema) is the customer's own text for each column: note its path as <dictionary_file> and apply it after introspection with sm describe-file --source metadata (2a.0), which applies every row one to one. Don't Read it into the prompt (the read is trimmed and paraphrased) and don't convert it into curate ops yourself. A dictionary in another shape (PDF, prose, an .xlsx) → ask for a CSV export; if there is none, read it as a doc as above.
If a published product schema (or the user names one — "use the ServiceNow data model online"): the user wants the standard fields grounded in the authoritative reference, not your training memory.
sys_dictionary/sys_choice, SAP DD03L, …). That's authoritative AND machine-readable — far better than scraping docs. So the real answer here is usually Phase 2a.0's sm enrich-metadata, not a web fetch. Note that intent now; it runs during enrichment.WebSearch/WebFetch the official developer/data-dictionary docs for the named product + the tables you discovered in 1.6. If you chose this path, the fetch is mandatory, not optional — do it once, upfront, and stash into $DATA_MODEL_DOC_TEXT (never written to disk). Note that vendor doc portals are often JS-rendered and return only nav skeletons (ServiceNow's does); when a fetch comes back empty, fall back to WebSearch result snippets / community pages and say so — don't silently substitute training knowledge.$DATA_MODEL_DOC_TEXT with the instruction: describe standard fields from this reference; if a field isn't in the reference or the data, mark it ai_unknown — do NOT fill it from general product knowledge. (This is the hole that let subagents drift to "from ServiceNow domain knowledge.")Stay anchored to the tables you actually introspected; don't invent fields the live DB doesn't have.
If a semantic-layer repo: use the directory from the follow-up card (a local clone / monorepo path — no upload needed since it's git-backed). Glob the definition files and Read them up to a budget (~30 files / ~250 KB total; if larger, prefer metric/model definitions and tell the user what you sampled). Skip compiled SQL and data files — you want the declared metrics/joins, not the warehouse output:
Layer Read these Carries LookML *.view.lkml,*.explore.lkml,*.model.lkmldimensions, measures (→ metrics), joins (→ relationships), sql_table_namedbt models/**/*.yml(esp.schema.yml),semantic_models/**,metrics/**,dbt_project.ymlcolumn descriptions, relationshipstests (→ FKs), MetricFlow metrics/measuresCube model/**/*.{yml,js}(orschema/**)measures,dimensions,joins
Stash everything gathered (doc text + repo definitions) as $DATA_MODEL_DOC_TEXT for enrichment — give entities/metrics/relationships found here confidence: inferred (a declared metric is a strong signal but still wants a human sign-off; FK-derived joins stay as the engine set them). Never written to disk — lives only in the enrichment prompt, then discarded. Skip → proceed.
When 1.5 saved no report SQL, export or screenshot, mark the report check skipped now, so it leaves the list; when Ask me as you go wasn't picked, mark 2g's step skipped the same way:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark reports=skipped
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark open_questions=skipped
The context is gathered: mark the step done and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark context=done
Mark the table step started and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark tables=in_progress
Before the full, expensive introspection, summarise the tables in the chat and ask which to keep — so staging/backup/scratch tables and dated snapshots can be dropped. The full grain/FK/description work then runs on only the kept tables, which on a big DB (hundreds of staging/snapshot tables) cuts the work to the tables that matter.
Run the discover pass — it lists tables + columns only (no grain, FK or count probes, so it's fast even over a tunnel); --row-estimates adds each table's size from one read of the catalog's statistics where the database keeps them, for the table picker, and never counts rows:
AGAMI_SQL_MAX_ROWS=200000 AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" discover --profile <profile> --db-type <db_type> --artifacts "<artifacts_dir>" --row-estimates --schemas <schema> <schema>
--schemas is the 1.3 pick; leave it out when you didn't narrow the schemas.
Why the
AGAMI_SQL_MAX_ROWSprefix — and why it must stay a prefix. The executor refuses (never truncates) any result over the row cap, default 1000. That bound is sized for a user query, where a runaway is the thing it exists to stop. A catalog read blows past it on schema size alone —information_schema.columnsfor a 500-table catalog is tens of thousands of rows — and the engine swallows that refusal silently, degrading to one round-trip per table, or reporting "catalog enumeration denied" when the catalog was in fact readable. So the two commands that read the catalog —discover(1.6) andintrospect(1.7) — run with a raised cap.enrich-metadata(2a.0) takes no prefix: it counts each dictionary table it reads and sizes that read's cap itself (up to 5,000,000 rows), so there is no number to pick for it.
- Inline on the command, never
export. An exported value is still set when Phase 6 runs the demo user query, quietly raising the bound for exactly the caller it exists to hold. The inline form dies with the process.- Never on
seed-examples(Phase 5). That command validates SQL which later runs as a real user query; validating under a raised cap green-lights examples that get refused in production.- Tell the user you did it, once, with the real numbers the commands print — and say their query-time cap is unchanged. See 2a.0 for the wording.
It writes the inventory to <artifacts_dir>/<profile>/.introspect/inventory.json and prints JSON with table_count and inventory_path. Discover writes no page: the table picker page is rendered only when the person picks Pick from a list (1.6p), and it saves its own answer; nothing waits on a pasted block.
Summarise it in the chat, ending the turn on a reply line (conventions: shared/question-cards.md).
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" inventory_summary.py --inventory "<inventory_path>"
It prints {tables, schemas, schemas_more, likely_noise, noise_all_copies, groups}. Show:
stg_*, *_bak, *_2023." (name the real patterns from groups.noise_by_pattern; leave the second clause out when likely_noise is empty).schemas (Schema | Tables), at most 15 rows, then the line "and schemas_more.schemas more schemas (schemas_more.tables tables)" when schemas_more is not null. Don't list tables one by one here: Pick from a list shows every one. With 10 tables or fewer, name them all in the sentence instead, so the card can be answered without the page.likely_noise with their why and, when it has one, the table it copies (copy_of), then "and N more", so the person sees what "Drop staging and backups" would remove (a real table that only looks like a copy shows up here before they press it). If they ask for the whole list, show up to 15 rows and "and N more".The summary and the table are the last thing in their message: a card after them in the same message would lose them (long-text.md). The reply line (the choices of one question, header Tables): Reply "pick from a list", "keep everything", "drop staging and backups" or "only some schemas", or type table names or patterns, like orders, customers or all crm_; ask to see any schema's tables or any table's columns, or type columns to leave out (schema.table.column).* Put the recommended choice first with "(recommended)" after it. Below, the card means this reply line, asked again. Handle the reply as the choices below; words that mean one of them count as it:
noise_all_copies is true, so it covers what Drop staging and backups would do.<N> tables.<M> likely-noise tables. Offer it only when likely_noise is not empty and does not cover every table. With 10 tables or fewer, mark it (Recommended) and put it first only when noise_all_copies is true (every flagged table has a same-named counterpart, so dropping them loses no data); otherwise list it after Keep everything without "(Recommended)", since a flagged table with no counterpart may be real data. With no noise, or when it covers every table, leave this option out; in the second case say that everything looks like staging or backups and ask what to keep.Names or patterns typed in the reply are the Let me name them answer below; there is no choice for it, since a choice that asks for typing gets picked with nothing typed (rule 5).
Act on the answer, writing the kept set to <artifacts_dir>/local/tmp/agami-keep.txt:
| Answer | Do |
|---|---|
| Keep everything | Skip the file. Run 1.7 without --tables-file; columns typed in "Other" still go to --exclude-columns (below). |
| Drop staging and backups | inventory_summary.py --inventory "<inventory_path>" --keep drop_noise --tables-out "<artifacts_dir>/local/tmp/agami-keep.txt" |
| Only some schemas | When the person shared questions or report SQL in 1.5, lead with the schemas they use: run the summary again as bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" inventory_summary.py --inventory "<inventory_path>" --used-by <each shared file>, without the AGAMI_SCRATCH_ONLY=1 prefix (it reads the person's own files, so they approve it at the prompt and see the paths) (agami-asked-questions.txt, the files in local/reconcile/inbox/, a semantic-layer folder's SQL), and when used_schemas is not empty make the first option The <k> schemas your SQL uses (Recommended), naming them in its description; tell the person in one line before the card how much of their material a pick would leave out when it drops one of those schemas. Then ask a follow-up AskUserQuestion, multiSelect. Up to 4 schemas: one option each. More: the options are groups.schema_groups (label, schema count and table count), and a picked group keeps all its schemas; "Other" takes schema names to add or to treat on their own. Name each group option's schema_count and tables. Add a "None of these" option only when that leaves fewer than 4 options; at 4, "Other" is the way out (a card holds 2 to 4 options). Then --keep schemas:<a,b,c>. |
| Pick from a list | 1.6p: the page, or the numbered list where a page can't open. It ends in the same --keep output, written to the same agami-keep.txt. |
| Let me name them (names or patterns typed in Other) | Write what was typed, as typed, with the Write tool to <artifacts_dir>/local/tmp/agami-pick.txt, then --keep pick:<artifacts_dir>/local/tmp/agami-pick.txt --shown 0 (this card shows no numbers, so a bare number names nothing). It reads table names (schema.table or a bare name), all <schema>, patterns with * (all crm_*, sales.*) and a leading everything except. A name that is both a schema and a table, or several tables that differ only in case, comes back ambiguous: ask which was meant. |
--keep prints {"tables_file", "kept"}; say how many tables are kept and pass --tables-file "<tables_file>" to 1.7. {"error": "no tables kept"} (status: needs_choice, nothing written) means the choice left no tables: say so and ask the same card again. A name that matches no table, or a bare name that matches several, comes back as {"unmatched": [...], "ambiguous": {...}} with status: needs_choice and nothing written: tell the person which ones, and ask the same card again. Never guess. Column exclusion is not asked here: personal-data columns are handled in review.
If the person asks to skip this ("just introspect everything"), proceed to 1.7 unscoped.
Showing what is there (when asked). "What's in sales?", "show me the columns of orders": list it in the chat from the inventory, then ask the same card again.
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" inventory_summary.py --inventory "<inventory_path>" --show "<schema | schema.table | table>"
A schema prints its tables with their column counts; a table prints its columns with their types. Show them as a markdown table (Table | Columns or Column | Type), at most 15 rows, and "and more more" when more is not 0. {"unmatched"} or {"ambiguous"} (status: needs_choice): say which name didn't match, or list the tables it could mean, and ask the same card again.
Columns to leave out, typed in "Other". Names of the form schema.table.column are columns to exclude from the build, whatever the table answer (Keep everything included) or on their own. Write them one per line with the Write tool to <artifacts_dir>/local/tmp/agami-drop-columns.txt and check them:
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" inventory_summary.py --inventory "<inventory_path>" --check-columns "<artifacts_dir>/local/tmp/agami-drop-columns.txt"
{"exclude_columns": [...]} → pass them to 1.7 as --exclude-columns <names…> and say how many columns are left out. {"unmatched": [...]} (status: needs_choice) → say which names are not columns and ask the same card again; never guess. Personal-data columns are asked about again on their own card after the build (Phase 4), and any column can be hidden later from /agami-model, so nobody has to find every column now.
Once the kept set is settled (or the person chose to model everything), mark the step done and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark tables=done
The spec names the tables, so there is no table pick: mark the step skipped and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark tables=skipped
When a model spec workbook was attached in 1.5, convert it FIRST and skip the 1.6 table card — the spec already names every table to model. Its outputs go under local/, outside the profile, so moving a partial model aside (1.8) never takes them with it (mkdir -p "<artifacts_dir>/local/model-spec/<profile>" first, as its own call):
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" model_spec_workbook.py parse --file "<workbook.xlsx>" --out "<artifacts_dir>/local/model-spec/<profile>/spec.json" --tables-out "<artifacts_dir>/local/tmp/agami-spec-tables-<profile>.txt"
It prints the counts it read (subject_areas, tables, joins, joins_approved, joins_with_condition, metrics, sensitive_columns, rules). Quote those numbers verbatim — never count a sheet by reading it. Exit 1 prints errors naming the missing sheet or column: show them and stop, the person fixes the workbook. Then run 1.7 with --tables-file set to that agami-spec-tables-<profile>.txt (the scratch folder is the only place the build reads a table list from) as ONE call — the single background build with its sm progress wait (1.7), never --append batches, however many tables the spec names. The spec is applied once, over the whole set, so read the whole set in one go.
The answer to 1.6's Pick from a list. A one-time page on 127.0.0.1 lists every table of the inventory, grouped by schema, with its row estimate and column count, a search box, select all / none per schema, and the likely staging and backup copies marked (unticked when noise_all_copies is true). Its Save tables button sends the pick to the helper waiting for it, the way the password page sends a password; nothing is pasted (question-cards rule 6a).
Where a page can't reach this computer, use the numbered list. In a remote or SSH session (SSH_CONNECTION is set), say in one line that pages open on this computer, which their browser can't reach from here, and go to The numbered list below.
Render the page and start the helper in the background (run_in_background), with <batch> the stamp bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" batch-id prints (the time plus a random part), so two pages never share a file. Each line is its own call, the second in the background:
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" render_table_picker.py --inventory "<inventory_path>" --save-to-helper --out "<artifacts_dir>/local/tmp/agami-tables-<batch>.html"
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" serve_page.py "<artifacts_dir>/local/tmp/agami-tables-<batch>.html" --decisions "<artifacts_dir>/local/tmp/agami-page-<batch>.json" --minutes 30
Wait for the helper's first line as rule 6a step 3 says (the Monitor tool, never a foreground sleep): {"url": "http://127.0.0.1:<port>/<token>/", "expires_in": 1800}. If no line comes, or the task exits, say so in one line with its last stderr line and go to The numbered list.
Post the link, then a card. Print the link in your reply, with when it expires, before the card (rule 6a step 4): "Pick the tables. Tick the tables to keep, press Save tables, then come back here and press I've saved it. The link works until (30 minutes)." Then one question (header Table list), "Save your pick on the page, then come back here.": I've saved it / Back to the cards. Handle both as rule 6a step 4 does: I've saved it with no final line yet says the page hasn't been saved and asks this card again; Back to the cards reads the helper's output first, offers to apply a pick it finds saved (rule 6a's Saved page question), and otherwise stops the helper with TaskStop and goes to The numbered list below: the page may never have opened (a cloud or web session can be remote without SSH_CONNECTION), and 1.6's card would only offer another page.
The helper's final line. {"status": "saved", "decisions": "<file>"} → write the kept set through the same command every other answer uses, which checks the file before it writes anything (the page and database it was rendered for, no other keys, and only names the inventory holds):
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" inventory_summary.py --inventory "<inventory_path>" --keep page:"<decisions file>" --tables-out "<artifacts_dir>/local/tmp/agami-keep.txt"
It prints {"tables_file", "kept"}: say "Keeping of tables." (<N> is the summary's tables), delete the decisions file and the page, and run 1.7 with --tables-file "<tables_file>". An {"error"} or {"unmatched"} (exit 1, nothing written) means the file isn't this inventory's pick: say so in one line and ask 1.6's Tables card again; never edit the file to make it pass. {"status": "expired"} → "The page expired before it was saved; nothing changed.", then 1.6's Tables card again.
The numbered list (when a page can't open). Every table, numbered, in the chat:
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" inventory_summary.py --inventory "<inventory_path>" --numbered
Show its list as it is, in a fenced text block: a line per schema, then one numbered line per table with its columns, its rows where known and a mark on a likely copy. This is the one place the chat lists tables one by one, because it is what the page would have shown. It lists the first 200 tables (shown is the last number in it, more how many it leaves out). Past 200 tables, say how many more there are, and that patterns and schema names reach every table; numbers stop at shown. Then one question (header Table pick), "Which tables should I keep? Type numbers, ranges or patterns in Other, like 1-12, 15 or all crm_ or everything except audit_.": Keep everything / Drop staging and backups (on the same terms as on 1.6's card) / Back to the tables card.
What is typed in "Other" goes, as typed, with the Write tool to <artifacts_dir>/local/tmp/agami-pick.txt, then --keep pick:<artifacts_dir>/local/tmp/agami-pick.txt --shown <shown> --tables-out "<artifacts_dir>/local/tmp/agami-keep.txt" (<shown> from --numbered), and the say-back is the same "Keeping of tables." The numbers are the list's own. {"unmatched": [...], "ambiguous": {...}} (status: needs_choice, nothing written): say which numbers or patterns matched nothing, or list the tables a name could mean, and ask this card again. A question typed there is answered first, then this card asked again (rule 5a). Columns typed as schema.table.column go to --check-columns, as on 1.6's card.
On entering 1.7, run:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>"
and do what its then says. If it does not say the model is already written, mark the step started, do what that call's then says (shared/task-list.md), and build as below:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark build=in_progress
This is the deterministic core — it replaces hand-authoring tables/columns/FK SQL/confidence formulas. Run it exactly as written, with the full quoted path (never cd into the scripts folder, never a shell variable for the path): that form is the one agami pre-approves, so it doesn't stop for permission.
Only if 1.6 did not already write the kept allowlist (its --keep writes it), write it yourself, one table per line, with the Write tool to <artifacts_dir>/local/tmp/agami-keep.txt; never a preset's source tables (sys_dictionary, sys_choice): 2a.0 reads those directly. Then one call, on one line:
AGAMI_SQL_MAX_ROWS=200000 AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" introspect --profile <profile> --db-type <db_type> --artifacts "<artifacts_dir>" --tables-file "<artifacts_dir>/local/tmp/agami-keep.txt" --exclude-columns <schema.table.column> <schema.table.column>
(The raised cap is the same one 1.6 explains — why. Without it a large schema's sql_tables / foreign-key reads are refused, the engine swallows it, and you get a model with no join graph and no error to show for it.)
--tables-file is the prune step's kept set (it also covers the no-catalog/probe-only case from 1.2). --exclude-columns marks the dropped columns excluded during the build — one validated write, no follow-up curate call. Leave either option out when it has nothing to pass; omit both only when the user kept everything or skipped pruning. (If a table name is bogus / can't be described, the engine now drops it with a note and — if nothing describes — errors clearly instead of writing a partial model.)
The build takes from a minute to many minutes, and the command prints nothing until it returns, which reads as hung. A local file is no exception: on the sample SQLite file it runs for over a minute, after checking joins against the data. So on every database, a SQLite or DuckDB file included, run it in the background and show progress from its log:
One background call. Bash with run_in_background: true, and a description the person can read in the app's background tasks, in their words: "Read the tables (Snowflake, 84 tables)".
Say once where to watch, the first time a background step starts in a run: "Reading your tables in the background." (and the progress page's link, when 1.0 opened one).
Keep the turn open and post progress with sm progress, one call per pass, doing what its then says after every pass, in a loop that stops when its then says the build has ended, or when its list shows the build step not started again (·), which is how a killed build shows (it writes no failure line, and the steps call it stopped after 30 silent minutes):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" progress "<root>" --wait 20
It returns as soon as the build's log moves on (or after 20 seconds) with line, ready to post: "Reading columns ▰▰▱▱▱▱▱▱ 12/34 tables", the bar drawn from the log's own counts and rounded down (never an estimate); a slow statement reads "Waiting on the database for 12 min: …", which means a statement is slow, not that the build has stopped. Its then is one of: post line; post line and update the task list from list; update the task list from list; nothing new, call this again; or the build has ended, run sm steps and go on. Do exactly that, and nothing else, each pass. Use this, not tail or a watcher of your own: agami's hook approves it with no prompt, and a turn that ends mid-onboarding leaves the build unwatched. If you do end your turn while it runs, say so in that message ("Still reading your tables; I'll carry on as soon as it finishes.").
Its output also carries list, the same step list sm steps prints, when there is a new one to show: the task list is updated from it when then says so (shared/task-list.md). No separate sm steps call per pass.
When then says the build has ended (also on a resume, when the log had already finished), leave the loop and run bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" once, and do what its then says. A build that finished needs nothing more here: go on to step 5. A build that failed or stopped: that sm steps call prints the problem as its say, with a then that says to say it to the person before going on: post its say, do what its then says, then handle it as the paragraph "The validator gates the write" below says (surface the errors and stop).
The onboarding step's label is the build step's line in that list, with the live count once the build's log has one ("Read the tables and joins — 12 of 34 tables"; right after the start mark it has none) and the final numbers when it ends; never type the count yourself.
When it exits, read the command's own output (the report, and the validator's verdict) as below.
Where background commands aren't available, a batched build keeps it legible instead (for a handful of tables, one foreground call is enough):
--append. Batching is your call, never a card (question-cards rule 9): say in one line how many batches you ran. Split the kept allowlist into batches of ~10–15 tables and introspect one batch per call, each a foreground command. Every call MERGES into the existing model (prior tables' columns and keys are loaded from disk, not read again; every join of the model is checked on the data again each call), so you end with the full union — and you report batch 3/5 (+12 tables) between calls. Write each batch's tables with the Write tool to its own file, <artifacts_dir>/local/tmp/agami-batch-1.txt, agami-batch-2.txt and so on, then run one call per file, each its own Bash call (never a loop), with --batch <n>/<N>:
AGAMI_SQL_MAX_ROWS=200000 AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" introspect --profile <profile> --db-type <db_type> --artifacts "<artifacts_dir>" --tables-file "<artifacts_dir>/local/tmp/agami-batch-1.txt" --append --batch 1/3
(--append on the first batch just creates the model — there's nothing to merge yet. The relationship pass runs each batch across the union, deduped, so the final batch yields the complete join graph. --batch n/N writes batch n of N as the log's first line, for the progress page.)The engine writes a flushed, throttled (~every 10%) per-phase log to <artifacts_dir>/<profile>/.introspect/progress.log (--progress <file> moves it elsewhere), each line stamped in UTC: discovered 52 tables …, columns+grain 30/52, joins: checking 78 on the data, joins checked 140/300, profiled 20/42 tables, done. A step that writes nothing for a minute adds waiting on the database for <N> min: <what> (table names only), so a slow statement never reads as hung; a build that fails ends it with failed: <reason>. Columns and keys are read for up to 4 tables at once, 1 when the profile signs in through a browser, the same limit the join checks use.
It builds + validates + writes the model at <artifacts_dir>/<profile>/: storage connection, proposed subject areas, per-table columns + types (catalog or value-inferred), PK→grain, other unique keys→unique_keys, FK→relationships with inferred cardinality (many_to_one/one_to_many/one_to_one, one-to-one when the join is on a whole key on both sides; a join only the data shows is unique keeps its label and lands unreviewed with a "looks one-to-one, confirm" note), column_groups on deep tables (≥30 cols), sensitive flags on PII (by whole-word column name, email-valued columns, and personal keys inside JSON values, named in a column caveat), cross-area edges, and a report. Relationships from unenforced-FK dialects (Redshift/Databricks/Trino) are confirmed when at least 95% of their values are found on the other side, else unreviewed; everything from probe mode is unreviewed. Every join is then checked on the data, and the report's ## joins checked on the data section lists the ones worth a look (values with no partner, or a referenced key that repeats, which multiplies rows): mention those in the Phase 7 summary in plain words. The report prints the capability mode per step (catalog vs probe) — surface that to the user so they know what was read vs inferred.
Join candidates (tested, not written). After the joins are built, introspection tests every column no join covers against each other table's one-column key (primary or unique) when the column's name matches the key or its type does — orders.cust_ref against customers.id, say (a column with a value list, or one column of a key over several, needs its name to point at the table) — and also when the database declares some foreign keys, for the columns they don't cover. Each test is a read-only aggregate over the whole column when its table is under 500,000 rows, and over a sample of 5,000 rows otherwise (spread across the table where the engine samples whole pages or blocks, else the first rows read); a key into a table over 3,000,000 rows is looked up for the keys read rather than read whole. Several share one statement, and up to 4 statements run at once, so the build holds up to 4 database connections beside its own (1 when the profile signs in through a browser). A run makes at most 300 of them, so a billed warehouse sees a bounded number of small queries. A column flagged sensitive, or whose sampled values look personal, is never tested at either end, and the report and the file carry only names and counts. None of these joins is written to the model. The report's ## join candidates section lists each with its match rate (+ orders.cust_ref->customers.id: all 3 values of orders.cust_ref are found in customers.id (whole table checked)), and the near misses with a -; it says so when the 300-probe cap stopped the scan, and names the tables whose columns it left untested (build them again with --append --tables-file to test them). A table's own key is never tested against another table's own key. The same list is in <artifacts_dir>/<profile>/.introspect/join_candidates.json, each candidate a ready add op with its evidence. An --append batch tests only pairs that touch a table it reads, keeps the stored check of every join between two tables an earlier batch read, and adds its candidates to the file rather than replacing the earlier ones; the report's first lines give the candidates found beside the joins written. Show the user the candidates and ask which are real joins; add each one they confirm with one call (written unreviewed, for sign-off in /agami-model).
Finish a scan the cap stopped, before the join cards. When join_candidates.json lists unchecked_tables, write them one per line with the Write tool to <artifacts_dir>/local/tmp/agami-unchecked.txt, then build them again; each run starts where the last stopped, so repeat while the run's report says pairs_tested_this_run above 0 (a wide table can make progress while the list stays the same), writing the file afresh from the new unchecked_tables each time:
AGAMI_SQL_MAX_ROWS=200000 AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" introspect --profile <profile> --db-type <db_type> --artifacts "<artifacts_dir>" --tables-file "<artifacts_dir>/local/tmp/agami-unchecked.txt" --append
Stop when the list is empty, when a run reports pairs_tested_this_run: 0 (it tested nothing new), or when a run fails; unless the list is empty, say so before Phase 2 and go on: " tables weren't checked for joins: <up to 5 names>." Never go on to enrichment with the list silently non-empty.
Show every join before asking about any of them. A card that offered "Add all 16" and "Only 1–8" without the joins themselves left the person nothing to judge by. First a table in the chat, one row per candidate from candidates, highest match first, numbered so the person can point at rows (question-cards rule 3); a chat table may show the identifiers:
| # | Join | Match |
|---|------------------------------------------|--------------------------------|
| 1 | leads.converted_contact_id → contacts.id | all 412 values |
| 2 | orders.cust_ref → customers.id | 4,812 of 5,000 sampled (96%) |
The join is the candidate's id without its schemas, -> drawn as →. The match says which check it was, from evidence.read, with matched, sampled and evidence.match_rate (a share; show it as a percent). Both count rows: of the rows read that have the key filled in, how many find a partner. On whole (every row read) it is "all <evidence.values> values" when matched equals sampled, else " of rows (<match_rate>)". On sample or first_rows it is " of sampled (<match_rate>)". Show the percent rounded down, as the summary does, so a join short of the 95% rule never reads 95%. Never call a whole-table check a sample, or a sample "all". At most 15 rows, then "and N more"; say how many near misses (low_overlap) were left out, without listing them. The table ends the turn with the reply line (a card after a table in the same message would lose the table, long-text.md): Reply "add the recommended", "review each" or "add none". Put add the recommended first with "(recommended)" after it when some have recommend: add (it adds exactly those; the others stay out); when none has recommend: add, add none (recommended) comes first instead. Handle the reply as the choices below; words that mean one of them count as it:
recommend: add.Join 1/3), the question in plain words ("Join Leads to Contacts by Converted contact ID?", rule 3b), options Add it (description: the match as in the table, "All 412 values match" or "4,812 of 5,000 sampled rows match (96%)", then what evidence.summary says about rows with no partner, which an inner join drops; preview: the join as in the table, then the ON condition, leads.converted_contact_id = contacts.id) and Leave it out, and, with more than 4 candidates, Add the remaining recommended, which adds only the joins not yet asked about whose recommend is add. The candidate's recommend says which one is recommended, never the model's own guess: put that option first with "(Recommended)" on its label, Add it (Recommended) when it is add (the column's name reads as a reference to the table, cust_ref or store_no, and the data matches), Leave it out (Recommended) when it is leave_out (its name does not read as a reference to the table, so the match can be chance: a count, a length or a code that runs 1, 2, 3 … like an id).Never offer a numbered range ("1–8") as a reply on its own: a range is only a label for joins the table names. The same reply line and cards are used for the joins a dictionary states.
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" curate "<root>" --ops-file "<root>/.introspect/join_candidates.json" --candidate "<id>"
Never accept them all unasked: a column can match a key's values by chance (two counters that both run 1, 2, 3 …). The name-guessed joins (a dealer_id beside a dealers table) are still written unreviewed as before and aren't listed again.
The validator gates the write — if it fails, the model is not persisted. Surface the errors verbatim and stop (this should be rare; the engine emits valid models).
Post one progress line, with numbers from the engine's output only. No card here: the build asks nothing. Every number comes from the report it printed (tables:, relationships:, subject_areas (<A>), capability modes:, deep tables:, sensitive columns:); never estimate, round up or fill a number the output didn't give. For how many joins came from declared foreign keys, count the relationship items with origin: "fk" in bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" review-items "<root>"; if you didn't run it, leave that clause out.
✓ Read <N> tables into <A> subject area(s) (<catalog|probe> mode); <R> joins, <F> from declared foreign keys; <S> columns flagged personal; <D> wide tables.
Add one finding on the next line when the report has one worth a person's attention, quoted from it: a suspected personal data (review): line, a large table line, or a note that dropped a table. One, not a list; none when there is none. Batched builds post batch 3/5 (+12 tables) between calls, then this line once at the end.
Empty tables — say so before going on. Read rows per table from bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" model-tree "<root>", its whole output, never filtered (measured during the build; null when it wasn't). When some tables have 0 rows, add to the progress line " of tables are empty" and name up to 5. When every measured table is empty, the build can't find joins or keys from the data, and every example will return nothing, so stop and say it plainly: "These tables have no rows: the database holds the structure only." Then AskUserQuestion, header Empty: Connect a different database (Recommended) (Phase 0a, a new name) / Continue with the structure only (descriptions, metrics and sign-off still work; Phase 6's examples will show 0 rows, so say that again there) / Stop here. A live run built a whole model on an empty demo database before anyone noticed.
Backstop reconciliation — if <N> is fewer than the catalog held, say what's NOT in the model and why (the 1.3 guard should have covered this up front; repeat it here so it can't slip). E.g. "Modeled 52 of 70 tables — left out public (17, separate Salesforce dataset) and pg_auto_copy (1, system). Say the word if you want any of them." A user who picked "all" should never have to diff the catalog themselves to notice a schema is missing.
Introspection proposed areas by name and joins only where the catalog or *_id names showed them. The spec replaces both, in one validated step that writes nothing unless the whole result validates and restores the previous model if anything fails:
Dry run and show the result:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" apply-spec "<root>" --file "<artifacts_dir>/local/model-spec/<profile>/spec.json" --dry-run
errors lists every problem at once (a table the build didn't find, an area a table names that the spec doesn't declare, a join column that doesn't exist) — show them all and stop; the person fixes the workbook and you re-run 1.6s.
A table "not in the introspected model" that IS in the database means its columns couldn't be read during the build (introspect's notes say dropped … no readable columns; a dropped connection is the usual cause). A second introspect into the same profile can't add it — once a model exists, its queries are scoped to the model's own tables — so move the partial model aside and rebuild once: mv "<artifacts_dir>/<profile>" "<artifacts_dir>/<profile>.partial-<timestamp>" (never delete it), then re-run 1.7 with the same --tables-file. If the same tables are missing again, stop and name them: the connecting role probably can't read them.
If the spec approves anything (joins_approved > 0, or a metric marked approved), ask ONE question: "The spec marks joins and metrics approved. Sign them off as you ()?" — Yes → pass --signer <email> --role owner; No → re-run without --signer after the person clears the Approved column. Never sign off in someone's name without asking.
Apply: the same command without --dry-run. Each join lands where the runtime serves it — in the area that owns both its tables, else as a cross-area join between the two owners — so the counts are joins = area joins + cross_area_joins.
Surface the counts from the JSON, verbatim: "Applied the spec: subject areas (<per-area owns / lists>), joins ( approved, with a condition, between areas), metrics, sensitive columns, rules; dropped introspected tables the spec doesn't name; replaced joins introspection had guessed."
Surface any notes too — in particular a metric flagged as a plain aggregate: ask once whether to drop it and put its name in the column description instead (re-run 1.6s after they edit the workbook), or keep it.
After a spec, the model's structure is the person's, not yours. Through the rest of the run: don't propose, add or re-infer joins; don't re-split subject areas (Phase 3 shows the spec's areas, it doesn't propose new ones); don't add metrics the spec didn't name (2c — the spec's metrics are already in); carry its rules as written (they are in datasource.md already). Enrichment still describes tables and the columns the spec's Columns sheet left out — the spec's own descriptions are human and a generated one is refused over them. Run 2b (entities) as usual: entities are the model's vocabulary (the business nouns questions are routed by), not structure, and a spec doesn't declare them. Regroup wide tables as usual too (the step at the end of 2a), even when the spec described every column: a spec doesn't declare column groups, so they're still the engine's name-prefix buckets.
When the model has validated (and the spec, if one was attached, is applied), and the join cards above are answered, mark the step done and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark build=done
Mark the step started and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark describe=in_progress
The engine gives structure; you add meaning. Load the model with cli bundle <root> --area <area> (or read the YAMLs). After each enrichment pass, re-validate (cli validate <root>) and never persist a model that fails. <root> = <artifacts_dir>/<profile>/.
One progress line per step, no card. After each step below, post one line with the numbers that step's command printed, and nothing invented: never a count you worked out by reading YAML, never a percentage you estimated. Leave out a step that didn't run.
| Step | Line | Numbers from |
|---|---|---|
| 2a.0 | ✓ Read the database's own dictionary: <n> columns described, <j> joins added | enrich-metadata's columns_enriched and relationships_added (left out when it printed enriched: false with no fetched) |
| 2a | ✓ Described <C>% of columns | sm coverage's coverage_pct |
| 2b | ✓ Added <E> entities | sm add --kind entity's applied |
| 2c | ✓ Proposed <M> metrics (<f> flagged, left out) | sm suggest-metrics's proposals, then --write's applied |
| 2d | ✓ Set units on <U> money columns | sm set-units's plan as applied |
Add one finding to a line when the step surfaced one, in the person's terms and quoted from what you read, e.g. "status stores 1–6; decoded as pending, paid, shipped, …" or "amount is in cents." One per step at most.
HARD RULE — decisions to you, plumbing to the engine. NEVER write a generator script (
build_ops.py,build_desc.py,enrich_*.py, a one-off that loops to build curate ops). It's the recurring failure mode and it's banned. When you have many edits, emit them as data and let a tested command apply them:sm describe-file(TSV of descriptions; a customer's CSV/JSON dictionary with--source metadata),sm enrich-metadata(in-DB metadata),sm set-units,sm suggest-metrics, orsm curate --ops-file <json>. You decide what (currency, which metrics, a column's meaning); the engine does the applying.
Many databases describe themselves. Metadata-driven platforms ship their own data dictionary + value-label tables (ServiceNow sys_dictionary + sys_choice, SAP DD03L, Salesforce metadata…), and plenty of ordinary schemas have code→label lookup/dimension tables. When that metadata is present it is authoritative — strictly better than LLM guessing or fetching JS-walled vendor docs. Always try it first:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" enrich-metadata "<root>" --profile <profile> --db-type <db_type>
When 0a.0's Source card named a product with a preset, pass it as --preset <name>. It auto-detects a preset (e.g. servicenow) or takes --preset, reads the dictionary/lookup tables straight from the database (they need not be in the model), and applies — in validated curate batches — column descriptions (stamped description_source: metadata, authoritative), choice_field labels, and reference/FK relationships (the caller_id → sys_user edges that <x>_id name-matching can't find). On ServiceNow this alone closes most of the column-coverage, enum-decode, and join-graph gaps deterministically. It prints what it enriched. Then hand-enrich only what it didn't cover (2a–2c below). --skip-references if you want descriptions/choices only.
No row-cap prefix here — the command sizes its own reads. A real platform dictionary can be hundreds of thousands of rows, past any number you would guess, so enrich-metadata counts each source table first and reads it under a cap of that count plus a margin, for that read alone. A source over 5,000,000 rows is not read: the command exits 1 with an error naming the table and its count — tell the user, and don't retry with a prefix (it would not change the outcome). Never pipe it through tail — that masks the exit code and a hard failure reads as success.
Then tell the user, once, using the numbers it printed (fetched is a per-role row count, on both the success and the nothing-applicable paths):
Read
<dictionary_rows>dictionary rows and<choice_rows>choice rows. Each dictionary read ran with a row cap sized to that table, for that read only — a data dictionary is far larger than the 1,000-row default. Your query-time cap is unchanged: a normal question that would return more than 1,000 rows is still refused rather than quietly truncated.
The second sentence is the load-bearing one. Without it a user reasonably concludes their safety bound was weakened.
A customer dictionary file (1.5). When the user gave a column dictionary as a CSV or JSON, apply it in one command, before you write any descriptions of your own:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" describe-file "<root>" --source metadata --file "<dictionary_file>"
The format comes from the extension (--format csv|json|tsv overrides it). CSV needs a table, column, description header (area / schema optional); JSON is a list of objects with those keys, or an object mapping "table.column" to its description. Matched columns are stamped description_source: metadata: the text is taken as written from the customer's dictionary and is not checked against the data (see #564), so don't present it as verified. A different case (ORDERS.Total) lands on the model's spelling and is listed under case_corrected; a SCHEMA.TABLE in the table column whose schema is in the model is listed under schema_prefix_stripped. A description a person wrote is never replaced: those come back under kept_human. A description whose provenance the run replaced (e.g. an earlier ai_unvalidated one, now metadata) is listed under provenance_changed. Rows that matched nothing come back under unmatched, each with a reason (no_table, no_column, ambiguous_table, ambiguous_column, malformed, empty_description); a CSV with broken quoting is refused as a whole with an error (exit 2). Tell the user how many columns were described and list every unmatched row with its reason (an ambiguous_table row needs an area or schema column to say which one). Never drop them, and never fix them by guessing: a dictionary entry for a table that isn't in the model is the user's call. Then describe only what the dictionary didn't cover (2a below), with source: ai. Your own descriptions never replace the dictionary's.
Joins the dictionary states. Once a dictionary is applied (this file, or 2a.0's enrich-metadata), turn the references it states (FK -> parent.pkey, FK to parent(pkey), "Foreign key referencing parent.pkey", "references parent.pkey", "Reference to the parent" when one table holds that entity) into join candidates, one check on the data each, outside the scan's 300-probe cap:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" dictionary-joins "<root>" --profile <profile> --db-type <db_type>
It adds each one that holds (candidates, evidence.found_by: dictionary, the dictionary line in evidence.dictionary) to join_candidates.json, one join per column, and writes nothing to the model. When candidate_count is above 0, show them exactly as the join candidates are shown after the build, the table ending its turn on the same reply line, adding each one the person confirms with the same sm curate … --candidate "<id>" call. A not_proven entry is a stated reference the data doesn't bear out: list each in one plain line with its match from match_rate ("The dictionary says Child's parent reference points to Parent, but only 61% of rows match"); unresolved names a table or column the model doesn't have, listed the same way. Never add either. Run it again after any later sm introspect on this model.
More than 12 tables: describe them in parallel. When sm areas adds up to more than 12 tables, the session has an Agent tool and the work splits into at least two subagents (two chunks), 2a and 2b run as one agami-enricher subagent per chunk of at most 12 tables, launched and applied exactly as shared/parallel-work.md says; the rules below are what each enricher follows. At 12 tables or fewer, or with no Agent tool, describe them yourself, one table after another, as written below.
The evidence for each table is the build's profile, not a handful of rows. Read it with bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" profile "<root>" --table <t1> <t2> (a few tables per call): per column how much of it is filled or blank text, its distinct count, MIN/MAX for numbers and dates, its most frequent values with their shares when it is coded (at most 25 values that repeat, none of them personal; never for a column named like a person's or party's name, a contact, tax or licence number), the stand-in values the build found, and findings (a column that is always empty, mostly blank or one constant value; dates after today on a column named for something that already happened; one date before another on nearly every row, the reverse of what their names say; a text column that mixes date formats); and each join's check on the data. The profile was read from the whole table under 500,000 rows and from a sample above it (read says which). A personal column carries counts only, and pay to a person (salary, pay rate, bonus) no range. Use a finding in the description in words that stay true after the next load ("the date the claim was paid, which comes before it was submitted" is not one; "holds the invoice date, not the payment date" is), never its figures. Only when a column's meaning still isn't clear from its name, its profile and the documents, read up to 5 rows of the columns in question, naming them: SELECT c1, c2, … FROM <t> LIMIT 5 with only declared columns that are neither excluded nor flagged sensitive. A star is refused, so never write one. Run profiling reads through bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" -m execute_sql --profile <profile> --build-profile --sql-file "<artifacts_dir>/local/tmp/agami-sample.txt" (the statement written there first with the Write tool; the file is overwritten by the next statement and holds only SQL text, never a credential, so never put a secret in it) (agami's own launcher runs the interpreter Phase 0a.5 resolved): it keeps every check except that it also allows information_schema's structure views (and pg_catalog's structure tables) and JSON/array functions such as jsonb_each or json_each over a declared column. Join with an explicit ON; USING and NATURAL joins are refused there. Don't use --no-safety for these. The database's first error line comes back under the fixed message, so a typo is visible. Rows you read are never written to disk — context only, then discarded. The profile's MIN/MAX of each date column is what Phase 5 anchors "last 30 days" to (the data's real MAX, not NOW()).
Build a per-schema prompt with $DATA_MODEL_DOC_TEXT first (dominant prior), then datasource.md, then tables/columns/profile. Always emit a 1-line table description. For columns, classify each into one of three — don't default everything to empty:
| Kind | Examples | What to write |
|---|---|---|
| Self-evident | id, created_at, email, name, gender, city | "" — the name + type already says it; a description would just restate it. |
| Informative | revenue_usd, status, margin_pct, utilization_pct | one line iff samples/doc support a fact the name doesn't (enum values, unit, derivation, a caveat). Else "". |
| Coded / opaque-but-systematic | EL_REVENUE_30D, WEST_ORDERS_12M, <TIER_A_6M>, XX_<metric> families | always describe — unreadable without the legend (see below). |
Coded-schema detection + legend expansion — the case that used to get wrongly left empty. Feature stores, wide denormalized marts, and coded analytic extracts encode meaning in column names via a small recurring token vocabulary: a category prefix (e.g. EL/HM/AP…), a window suffix (_30D, _6M, _12M), a bucket (_0_30, _TIER_A), a threshold (_LT_1K, _LT_10K), a metric stem (_REVENUE, _QTY, _RECENCY). When the same tokens recur across many columns:
$DATA_MODEL_DOC_TEXT + datasource.md. For any token whose meaning isn't evident, ask the user in one batched question rather than guessing (this is the same decode 2b needs; do it once and share it).(prefix, metric, window, threshold)) and compose each description from it, then emit them through the same sm curate batch. This is exact, internally consistent, and costs zero per-column LLM tokens. e.g. EL_REVENUE_30D → "Total revenue from the Electronics category over the last 30 days"; WEST_ORDERS_12M → "Number of orders in the West region over the last 12 months"; EL_ORDERS_LT_1K_90D → "Number of Electronics orders under 1,000 placed in the last 90 days." (Use the user's actual token vocabulary + domain, not these placeholders.)key_terminology (term → definition) — abbreviations and codes a reader needs (an acronym → its expansion; a status/type code → its meaning). Decode once, write both — the per-column descriptions (what shows in the explorer + feeds the SQL generator's column context) AND the glossary. Write it with the packaged command (a JSON object {term: definition, …}); it merges over any existing terms, validates, and commits:
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" set-terminology "<root>" --file "<artifacts_dir>/local/tmp/agami-terminology.json"
The glossary is rendered into datasource.md's ## Key terminology by org-draft (which also auto-seeds enum legends from choice_field columns) — so it survives a regeneration and is never a bare placeholder. Do NOT skip this on a code-dense schema (abbreviations, master-coded values): an empty Key terminology on a DB full of codes is a real miss.Don't skip a coded column because "the legend covers it" — the legend lives in a different file; the per-column description is what the explorer shows and what NL→SQL reads. A wide coded table (hundreds of columns) should finish at ~100% column coverage, not ~3%.
Value-enum decode — FILL choice_field for coded-VALUE columns (the highest-leverage structured win). Distinct from the coded-name legend above: this is a column whose stored VALUES are codes — a severity of 1/2/3, a state of 1/2/3/6/7, a priority of 1–5, a short status/type code. Introspection now seeds a choice_field skeleton — the column's complete set of values with blank labels (e.g. {"1":"","2":"","3":""}, not a single placeholder), so the keys already exist and you only fill the labels. The keys come from the catalog when it declares them (a Postgres enum, a MySQL ENUM, a CHECK (col IN (...))), on a table of any size; otherwise, on a small table only, from a SELECT DISTINCT over the whole column, kept only when it has at most 25 values. A column with no skeleton has more values than that, is on a large table, or is a key, measure or year — don't invent a list for it from a sample. Keys are the values exactly as stored: never trim or re-case them ('Open ' and 'Open' are different values; a caveat on the column names such pairs). Your job is to fill the labels — from samples + $DATA_MODEL_DOC_TEXT, or a lookup/choice table when the DB has one (e.g. ServiceNow sys_choice: SELECT value, label FROM sys_choice WHERE name='<table>' AND element='<column>' — read it once and apply, don't hand-guess). Write it as a structured choice_field edit op, not just prose:
{"op":"edit","kind":"table","area":"<area>","name":"<table>","column":"severity","field":"choice_field","value":{"1":"High","2":"Medium","3":"Low"}}
Why structured beats prose: the SQL generator translates "high severity" → severity = 1 and labels result rows from the map deterministically — a decode buried in the description can't be applied programmatically. Fill the skeleton on every coded-value column in the same sm curate batch as the descriptions; leave a label blank only when no sample/doc/lookup reveals it. (The filled map also auto-seeds the glossary via org-draft.) Self-labeling value sets (a region of North/South/East/West) can keep choice_field as the values themselves or be cleared — they need no translation.
Write descriptions with sm curate edit ops — never hand-edit the table YAML, and never write a throwaway generator script to build the ops. Build one ops array and run it once; it validates the whole model + commits + reverts on failure. The op does NOT need area — curate resolves which area owns a table/column by name, so you do not maintain a table → area map (that map is exactly what used to push the LLM into writing an enrich_gen.py; it's gone). Shapes:
{op:edit, kind:table, name:"<table>", field:"description", value:"<text>", source:"ai"}column:"<col>"Pass area only to disambiguate a bare name that exists in two schemas (curate skips an ambiguous op with a clear "pass an explicit area" reason rather than editing the wrong one). Always include "source":"ai" on every generated description — this stamps description_source: ai_unvalidated so the description earns trust through use (agami-query surfaces it in the answer receipt for confirmation the first time a query actually uses that column, instead of forcing an upfront review of hundreds of descriptions). Skip any column that already has a description (so a partial hand-edit or a reintrospect merge is never clobbered):
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" curate "<root>" --ops-file "<artifacts_dir>/local/tmp/agami-descriptions.json"
| Column | Bad (reject) | Good (keep) | Empty (preferred) |
|---|---|---|---|
id, created_at, email, name | "Primary key" / "When created" / "Email" | (always empty — self-evident) | "" |
customer_id | "The customer ID" | "FK to customers.id; 1:N with orders" | "" if nothing to add |
status | "A status code" | "lifecycle: pending → shipped → cancelled" (only if enum known) | "" |
EL_AOV_90D (coded) | "AOV value" | "Average order value for the Electronics category over the last 90 days" (from the decoded legend) | — don't leave empty |
v_1, tmp_col, x | "A value" | (leave empty — opaque, no decodable structure) | "" |
What NOT to invent: meanings for truly opaque single columns (v_1, tmp_col, xyz) that have no decodable token structure and no sample signal. Business semantics not present in the samples/doc. Name translations on self-evident columns (amt→"amount"). Write the decodable legend; don't fabricate the rest.
For an opaque column you genuinely can't read, say so — don't leave it silently blank. There are two kinds of empty description, and they must be distinguished:
id, created_at, email, a clear name) → leave the description empty AND leave description_source unset (null). The name already says it; nothing to flag.xyz, v_1, tmp_col, a code whose meaning no sample or doc reveals) → leave the description empty BUT set description_source: "ai_unknown" via a curate edit op ({op:edit, kind:table, area, name:<table>, column:<col>, field:"description_source", value:"ai_unknown"}). This records "agami looked and couldn't tell" — the human knows what xyz is, and the explorer + answer receipts surface these so they can fill it in. Don't guess a meaning to avoid the flag; the flag is the honest answer. (Do NOT mark a self-evident column ai_unknown — that's noise.)For large schemas (>100 tables) batch 50 at a time; narrate [batch 2/4] …. Validate after each schema; on failure, surface errors and continue with the rest, then report which need attention.
Regroup wide tables into SEMANTIC column groups (do this right after describing their columns). A deep table (≥30 cols) gets column_groups from the engine, but those are a deterministic name-prefix split — buckets like is, last, latest, created, bp — not concepts. They exist only so the explorer can collapse a wide table; they're a fallback, not the goal. Having just described every column, you are positioned to cluster them by meaning into a handful of named groups that read like mini subject-areas — e.g. identity, location, lifecycle_timestamps, telemetry, swap_details, alerts, flags. Keep it to ~5–10 groups; every column must land in exactly one (the validator rejects orphans on a deep table). Describe every group too: the engine's descriptions ("Columns named exp* (grouped by prefix)") don't fit regrouped columns, and an agent reading the schema picks which group to fetch by its description. Say what the group holds and which questions need it, in one line, e.g. "travel: destination, trip dates and foreign-activity fields; use for questions about where or when someone travelled." Apply both as two curate edit ops per wide table:
[{"op":"edit","kind":"table","name":"<wide_table>","field":"column_groups",
"value":{"identity":["..."],"location":["..."],"lifecycle_timestamps":["..."],"telemetry":["..."]}},
{"op":"edit","kind":"table","name":"<wide_table>","field":"column_group_descriptions",
"value":{"identity":"...","location":"...","lifecycle_timestamps":"...","telemetry":"..."}}]
Send these in the same sm curate batch as the descriptions (or a follow-up batch). Only worth doing on genuinely wide tables — narrow tables have no column_groups and need none. A wide table whose group descriptions are all the engine's own wording hasn't been regrouped yet: "Columns named … (grouped by prefix)", or one of its fixed lines for identity, references, codes, flags, audit, measures, dates and misc ("Primary keys and unique identifiers for this table.", "Numeric columns that can be aggregated (summed or averaged).", and so on). Check for that before Phase 7 and do the rest.
Column-pass completeness gate (MANDATORY — do not skip the column pass). After enriching, run:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" coverage "<root>"
ok: false with unenriched_tables lists tables that got a table description but no column descriptions at all — i.e. you enriched the table layer and skipped the columns. That is not done: go back and run the column pass on those tables (describe each meaningful column from sampled values; mark genuinely-opaque ones ai_unknown; self-evident id/timestamps may stay blank). A wide coded table must finish near 100% described, not 0%. This is also enforced downstream — seed-examples refuses (refused: "columns_unenriched") while any table is unenriched, so you cannot reach the trust dashboard on naked columns. Don't proceed to 2b until coverage returns ok: true.
Propose entities[] per subject area — the names users actually say. For each, fill name, plural, other_names (synonyms), maps_to (table+column, one primary: true), and — for opaque-identifier columns — a value_pattern regex (e.g. a VIN ^[A-Z0-9]{17}$, a BP-prefixed serial) so the runtime can recognize literals. Ground these in column names + samples + the domain doc; don't invent entities the schema doesn't support. Because these are LLM-proposed, write them confidence: inferred, review_state: unreviewed so they surface in the Phase 4 pre-seed review (seeds reference entity vocabulary).
Don't stop at id columns — wide / denormalized tables hide dimensions a maps_to-on-an-id scan misses. When a schema is denormalized to one grain (e.g. one row per customer, every table keyed on the same id), an id scan finds exactly one entity and quits — yet real business dimensions are still there, encoded two other ways. Look for both, discovered from the actual columns + samples, never hardcoded:
XX_<metric> repeated for several XX, or <metric>_<period>) means that token is a dimension (a product line, a region, a time bucket). Decode it from evidence — column descriptions, sample values, the domain doc; if a code's meaning isn't evident, ask in one batched question rather than guessing. A prefix dimension has no id column, so it isn't a maps_to entity — record the decoded legend in datasource.md ## Key terminology and fold the expansion into each affected column's description, so NL→SQL can map a phrase to the right prefixed columns.maps_to the most representative such column; capture distinct sampled values as other_names/a value_pattern cue) so a user naming a literal value resolves to those columns.If, after this, a single-grain schema genuinely has one entity, that's the right answer — say so. The point is to check the two hidden shapes before concluding "one entity," not to manufacture entities.
Write them with the packaged command, not by hand — build a JSON array and run it once (it validates each item, writes subject_areas/<area>/entities/<slug>.yaml, validates the whole model, reverts on failure, commits). Never author a throwaway script to loop. The canonical entity YAML shape is shared/metric-entity-shape.md — never read another profile's artifacts to copy it (see the boundary note under 2c):
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" add "<root>" --kind entity --area <area> --file "<artifacts_dir>/local/tmp/agami-entities.json"
Metrics come from two sources, handled very differently. Always prefer declared metrics — schema-only inference is a shallow guess (it finds start→end durations, and flag rates when asked; it misses the domain KPIs a business actually tracks — refund rate, repeat-purchase rate, cohort retention, fulfillment SLA — because those aren't visible in column names).
A table whose caveats begin "Rows repeat about N times per " holds each record on several rows (introspection measured it; often a view joining a record to its stages). Any metric on it counts records with COUNT(DISTINCT <key>), never COUNT(*), and averages or sums per record, not per row; never write a grain of <key> alone for it. suggest-metrics proposes its distinct-record count (<table>_distinct_<key>_count) and no duration average on it.
(A) Declared metrics — extract in FULL, no cap. If the user attached a semantic-layer repo or a metrics file in 1.5 ($DATA_MODEL_DOC_TEXT), those are the org's real definitions — pull every one, don't sample to 4:
measure {} → metric: type + sql → bindings, description → description + calculation, label → description when there is no description (below), label+view_label → other_names.metrics: / semantic_models[].measures (MetricFlow) → name, agg+expr → bindings, description → description + calculation, label → description when there is no description (below), label → other_names.measures → sql+type → bindings.description + calculation (below), formula → bindings.description and calculation are two fields with two jobs — write both, never one copied into the other. description is a one-line label (≈60 characters): is this the metric I want? It is all the agent sees of a metric before it opens the metric's table — metric_index lists it on every schema call and the metric search matches it — so a metric without one is left out of the index entirely (the validator warns metric_undescribed). calculation is the full definition: what is counted, the filters, the traps, and when to prefer it over a sibling. The agent writes the SQL from it once the table is open. So from a declared source, fill both every time, falling back in this order:
description ← the source description's first sentence; else its label, if the label says more than the metric's name; else one line you write from the definition.calculation ← the source description in full; else a sentence you write from its type/agg and sql/expr (what it aggregates, over which rows, with which filter). Never leave it as the label: it is required, and a label is not a definition. A description that only restates the name ("Incident count" for incident_count) counts as none.Translate the declared SQL/agg to the profile's dialect for bindings, set source_tables, write confidence: inferred, review_state: unreviewed (declared = strong signal, still wants a human sign-off on the /agami-model Review tab). If there are many (> ~8), don't funnel them through a 4-item picker — write them all and tell the user once: "Added N metrics from your <LookML/dbt/file> — review or trim them in /agami-model." (Offer a single "add all N / let me pick a subset" confirm if you want, but never silently drop declared metrics to fit a cap.)
(B) Inferred metrics — infer a sensible set for BULK review, don't ask for 4. Run sm suggest-metrics "<root>" --profile <profile>: it infers per-table measures — start→end durations, never a plain aggregate (see below), and no flag rate unless asked (below) — and prints them without writing anything (a dry run). --profile test-runs every binding against the database first (one bounded read per table — on a pay-per-scan warehouse such as BigQuery or Snowflake that read is billed, so say so before running it there; without --profile the output notes the bindings were not test-run). Each proposal shows its binding, calculation, source_table, any error (a binding that failed — never written) and flags: degenerate (constant, all zero or NULL), low_confidence (a table under 50 rows), not_test_run (a table defined by SQL whose read failed, so its bindings are unproven), ambiguous_pairing or audit_column (a duration whose start/end pairing needs a person's eye). Show the user the proposals, flagged ones with their reason, then re-run with --write — it writes the unflagged ones; add --names <metric> … to keep only some, or to keep a flagged one the user chose. Every written metric is proposed, because each picks a condition or pairs two columns. An unsigned metric is still used — the answer carries a warning that it is unreviewed (Rule 1) — so drop a proposal nobody would ask for rather than leave it for the queue; the user reviews the rest on the Phase 4 cards. Reserve AskUserQuestion only for a bespoke KPI the user describes in words that the column shapes don't imply.
Flag rates — only the ones the business defines. By default suggest-metrics proposes no share-of-true rate per boolean column (<table>_<col>_rate): a boolean column is a dimension and a filter, and the agent can compute its share from the column when a question needs it. The output carries one summary instead, flag_rates: {available, columns, labels, hint} — the boolean columns that could each have one. When the customer's definitions (a data dictionary, spec, KB, metrics file from 1.5) name a share-of-true rate as a measure, request exactly that one and cite the document: sm suggest-metrics "<root>" --profile <profile> --flag-rates <table.column>[,<table.column>…] --cite "<document>", show it, then re-run with --write (its description becomes Defined in: <document>.; when you humanize it below, keep that sentence at the end of the description). A name that matches no boolean column comes back in errors — fix the name, don't drop it silently. A table name in more than one schema or subject area is refused before anything is written, with the matching columns listed: name it schema.table.column (the column is after the last dot), or pass --area. Otherwise don't request any: mention the summary line to the user once, naming the columns by flag_rates.labels, never as table.column (question-cards rule 3b): "3 yes/no columns, such as In stock on Widgets, could each have a metric for the share of rows where it is true. Say if any is a KPI you track.", and add only the ones they name (flag_rates.columns, in the same order as the labels, is what --flag-rates takes). --flag-rates all restores a rate for every flag column; don't use it in onboarding. Rate metrics already in a model are left as they are; to clear out old ones, the explorer's Review tab (/agami-model) has Reject all for proposed metrics.
Don't hand-add the plain ones it deliberately skips. A {table}_count = COUNT(*) or a {table}_total_{col} = SUM(col) is not a metric: the column's aggregation class is enforced on every statement with or without a named metric, and everything such a metric could carry already reaches the agent on the table it opens — the column's unit (which the formatter carries through SUM/AVG by itself), the table's and column's caveats, and the table's grain. So the entry adds a name and nothing else; on a wide model that pattern was 137 of 175 metrics, each listed by its own name, burying the real ones. A table with no metric of its own is the expected outcome, not a gap to fill: mark the columns' aggregation and unit correctly and put caveats on the column or table, and spend metric effort on the ones with real definitions (ratios, multi-table measures, anything with a filter or a business rule in it).
Run order matters — describe columns FIRST, then suggest metrics. suggest-metrics skips columns agami couldn't read (description_source: ai_unknown) — it won't propose a metric on a column it can't explain (the prose would just restate opaque SQL like "Fraction of alm_asset where active_to is true"). Its output reports skipped_opaque: N. So: settle 2b/2c column descriptions first, run suggest-metrics, and after the user describes any still-opaque columns (the explorer's "couldn't read" pile, or a later pass), re-run sm suggest-metrics "<root>" --profile <profile>, show the new proposals, then --write — it's incremental (skips names already written), so the newly-described columns pick up their metrics with no duplicates. This is the re-pass: describe → suggest → describe more → suggest again.
Then HUMANIZE the inferred prose (B-metrics only). suggest-metrics writes a calculation that is a mechanical restatement of the SQL ("Fraction of alm_asset where active_to is true") and no description (a cited flag rate has only its Defined in: <document>. line) — what a metric is for is judgement it cannot derive. Once the columns are described, write both, grounded in the column/table descriptions + the glossary (NOT product memory):
description — the one-line label: "Share of assets still in their active lifecycle window".calculation — the full definition, carrying anything the agent must know to write it: "Fraction of assets whose active_to flag is true — the asset is inside its contracted lifecycle window. Retired assets keep their rows with the flag false, so the rate falls as the estate ages."Apply as one sm curate batch of {op:edit, kind:metric, area, name, field:"description", value:"<label>"} and {…, field:"calculation", value:"<definition>"} ops (decisions to you, plumbing to the engine — never a generator script). Leave declared (A) metrics alone — their prose already came from the source. Drop a proposal rather than describe it when you can't say what it is for: a flag rate on a column nobody would ask about is noise in the review queue, not a metric.
In the SAME batch, fill other_names (aliases) where the org has well-known ones — a metric with empty other_names only matches its literal name, so a user asking for "MTTR" / "AHT" / "P1 count" misses a metric named incident_avg_duration_days. Add the aliases the org actually uses: from the metrics file / glossary if provided, or the standard abbreviation for that metric type (a mean-time-to-resolve duration → MTTR; average handle time → AHT). Only add genuine aliases — don't pad with restatements of the name. {op:edit, kind:metric, area, name, field:"other_names", value:["MTTR", …]}.
For every metric (A or B) fill name, a one-line description (the index label — without it the metric is left out of metric_index), prose calculation (the full definition — required), per-dialect bindings (the SQL), source_tables, other_names. The canonical YAML shape is shared/metric-entity-shape.md (synthetic example). Write them with the packaged command — build a JSON array and run it once; never hand-write each YAML and never author a throwaway loop script. It validates each item, writes subject_areas/<area>/metrics/<slug>.yaml, validates the whole model, and reverts the batch on failure:
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" add "<root>" --kind metric --area <area> --file "<artifacts_dir>/local/tmp/agami-metrics.json" --profile <profile>
Never read another profile to learn the shape. Do not glob or read other profiles' artifacts (e.g.
find <artifacts_dir> -path '*/metrics/*.yaml', or reading<artifacts_dir>/<other-profile>/…) to "copy the binding shape." That crosses the profile boundary — in a hosted/multi-tenant deployment it's a tenant-data leak (onboarding one customer must never read another's model), and even locally it risks lifting another profile's filters / calculation text into this one. You don't need to: the packagedsm addcommand validates every item against the schema. Get the shape fromshared/metric-entity-shape.mdand the profile's own schema — never a sibling profile. Don't propose metrics depending on choice-field literals you didn't detect, or cross-area metrics unless a cross-area edge wires the join. A metric whosesource_tablessit in two subject areas goes in the datasource's cross-area list —--area _cross, which writescross_subject_area_metrics.yaml:
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" add "<root>" --kind metric --area _cross --file "<artifacts_dir>/local/tmp/agami-cross-metrics.json" --profile <profile>
--profile runs each metric's SQL over zero rows on the database first, and writes nothing if one fails: its test_run names each failing metric with the reason (a column the table doesn't have, a text code compared to a number). Fix those bindings and add again; never drop --profile to get past it. A test_run of {"connection": {"error": …}} means the database could not be reached (credentials, network, a missing driver), not that a metric is wrong: nothing was written, so fix the connection and add the same file again. A metric over several tables comes back not_test_run, and its first real check is Phase 6. --area must be _cross or a subject area datasource.yaml lists; any other name is refused with the list of areas (a file written under an unlisted area would never be loaded).
A missing value is not a zero. Write bindings so NULL propagates: a row whose input is missing gets no result, not an invented one. Don't wrap a column in COALESCE(col, 0) / IFNULL / NVL / ISNULL to make a formula return a number on more rows — when the column's description says NULL means "not recorded" or "not assessed", the zero is made up, it pulls averages and rates down, and every session copies the binding. Fill with a constant only when the column's metadata says a missing value means zero ("NULL means none"), or when the definition you were given writes the fill into its formula — then keep it, and say in the metric's calculation where it comes from ("the KB formula counts a missing percentage as 0"). A total over no rows (COALESCE(SUM(x), 0)) is fine. Tell two cases apart: a recorded value that is missing (a staff count nobody entered) stays empty; no related rows at all (a hub with no supply records serves no disasters) is often a real zero — decide it per metric from what the formula means, and say which you chose. The validator warns on a constant fill when neither the column nor the metric's calculation gives that reason (metric_null_filled). To average the values that exist, write AVG(col) for one column (it leaves NULLs out); for several columns write the sum of the present values over the count of the present values, SUM(COALESCE(a, 0) + COALESCE(b, 0)) * 1.0 / NULLIF(COUNT(a) + COUNT(b), 0) (the * 1.0 stops integer division on PostgreSQL, SQLite and SQL Server), with no VALUES list or per-row subquery — the validator accepts that fill, since the zero is never counted. Never put an aggregate inside another (AVG(SUM(x)), or a SUM in a percentile's WITHIN GROUP): sm add refuses it; use a second-order metric (shared/metric-entity-shape.md). Every model's derived context already tells the query path to keep rows whose value cannot be calculated, shown empty and last, and to leave them out of averages and rates — so a metric doesn't need its own fill to stay usable.
"Today" means CURRENT_DATE, never the data's last date. A metric defined against today or now (days since start, age, days until due, overdue) binds CURRENT_DATE — or the engine's equivalent (NOW(), GETDATE(), SYSDATE) — and its calculation says the result depends on the run date. Don't measure to a fixed date or to MAX(<date column>) to make the figure reproducible: when the data isn't loaded up to today (a stale extract, a test or demo set) that silently changes the answer and which rows qualify, and it overrides the definition. Don't write how far the data lags today into a caveat either: that changes with every load, and the answer's receipt is where freshness shows. The validator warns when a metric's text says today but its binding doesn't use the current date (metric_today_not_current_date).
A share of a total is a ratio of totals. When a metric divides two amounts that add up (sales, watts, hours, counts), bind the group's value as SUM(numerator) / NULLIF(SUM(denominator), 0) over the rows where both are known — not AVG(numerator / denominator), which weighs a small row the same as a large one and disagrees with the totals shown beside it. Do this even when the definition you were given writes the formula for one row ("(solar + wind) / total output, per reading"): a binding with no aggregate leaves the query to average the rows, which is the same mistake one step later, so bind the share as the ratio of totals and say in the calculation that a group's value is the ratio of its totals. Average the per-row ratios only when the metric really means that — an average per-student score, or a definition that scores each plant or fund and then averages them — and say so in its calculation ("the average of each row's ratio"). Mark the amount columns aggregation: additive while you are there: the validator warns on AVG of a ratio of two additive columns (metric_avg_of_ratio), and cannot see columns whose class was never set.
From samples + the domain doc, add provider-portable cleaning where evidence supports it:
caveats[] on table/column/entity): data-quality notes, anti-patterns (e.g. "filter on the event date, not the load date"), dedup warnings.calculation or metric description says "NULL means the value was not recorded", not "427 of 670 accounts have a value", "covers only 40% of rows", "values range 49–142 here" or "twelve of forty sites report it". A count measured today is wrong after the next load, yet it reads as part of the definition and gets repeated in answers. If a figure helps the reviewer decide, put it in the question you ask them, not in the model. The validator warns on such figures (measured_figure); constants that define something, such as thresholds, weights, unit factors and scales, are fine, and so is how the formula behaves ("returns 0 when no row meets the threshold").'0.73%' means 0.73 percent (0.0073 as a ratio) even when every value is below 1; a column documented as "average annual return (decimal)" is that column even when its values look ten times too large. Don't decide the label is wrong and build the model on your own reading — no "the % is wrong, this is a 0–1 ratio" rule, no switching to a neighbouring column with a similar name, no rescaling. The data may well be wrong or oddly scaled, but that is the data owner's call: write what you saw as a caveat ("every value is below 1 although the field is labelled %; confirm the unit") and ask the user in plain words which reading is right. Change the binding only on their answer.regexp_replace(...) for bracketed text, TO_TIMESTAMP(...) for epoch). Must parse as SQL in the datasource's dialect (validator checks), so a Postgres CASE WHEN code ~ '^[0-9]+$' THEN code::int END is fine on a Postgres model. A field inside a JSON column: there is no separate JSON-path field — put the transform on the JSON column and have it extract the key itself, e.g. Postgres (profile->>'signup_date')::date, SQLite date(json_extract(profile, '$.signup_date')), DuckDB CAST(json_extract_string(profile, '$.signup_date') AS DATE), and say in the column's description which key it reads.default_filters[] on a table): soft-delete / tenancy filters that state what the org means by the table (use the {alias} placeholder, e.g. {alias}.deleted_at IS NULL). Declarative only — they are not AND-ed into a query for you; the query path reads them and writes in the ones a question needs. Declaring one is still worth it: the trust receipt reports, per table reference, which of them the statement that produced an answer applied and which it omitted, so an author sees whether their definition was honored.large table lines): each line names a table of about a million rows or more and its date columns; the build seeded recommended_filters with all of them (when there are six or fewer). On a warehouse many are load or audit stamps (the row's own created/updated/valid-from/valid-to) that no business question filters on. For each table with date columns, ask in plain words: "orders has about 5 million rows. When someone asks about a period, which date do they mean?" — a multi-select of at most three of its date columns (the likeliest business dates; leave out the load and audit stamps) plus None of these, because AskUserQuestion takes four options; the built-in Other lets them type any other column. Keep only what they pick; None of these clears the list (the right answer when the table is narrowed through a joined date or period table rather than a column of its own). A table with no date columns: skip it. Write each answer with the recommended_filters edit op below, which leaves the row count alone. Up to four tables per AskUserQuestion call; more → another call.possible placeholder values): each line is a value on a small or dimension table that looks like a stand-in rather than data — a negative key among positive ones (-99999), a date before 1901 or more than 50 years ahead (2099-12-31, 9999-12-31, a MySQL zero date), a 999999-style value, or filler text such as '-' or 'N/A' on a large share of rows. agami can't tell which kind each one is, so ask; never pick a meaning yourself. Show each finding in plain words, naming tables and columns in words, not as identifiers (question-cards rule 3b), and putting the lines of one row together ("The Date dim table has a row keyed -99999 dated 2099-12-31, fiscal year 2099. Is it Unknown, still-current, or not-set?"), with the options Unknown (a stand-in for a missing member: left out of breakdowns, date ranges and latest/earliest, kept in totals), Still current (an open-ended row, the one "as of now" questions want), Not set (treated like NULL) and Real data. Up to four findings per AskUserQuestion call. sm review-queue "<root>" lists the same findings under placeholders, each with its question already in those words and the column's label. Write each answer with one placeholder op, signed off by the person who answered (--signer <their email> --role <their role>; a system sign-off is refused):[{"op":"approve","kind":"placeholder","name":"date_dim","column":"date_key","value":"-99999","meaning":"unknown"},
{"op":"approve","kind":"placeholder","name":"customer_history","column":"valid_to","value":"9999-12-31","meaning":"current"},
{"op":"reject","kind":"placeholder","name":"shipments","column":"status","value":"-"}]
meaning is unknown, current or not_set; reject records that the value is real data. Approving also writes the meaning as a caveat on the column. Nothing filters a query: the query path reads the meaning and decides per question. A finding the person skips stays in the /agami-model Review tab under Placeholders, and a refresh (--append) keeps every answer and never asks about it again.
sm suggest-units "<root>" — don't hand-roll a name regex (a bare count pattern matches inside discount and silently drops discount_amount; the command's matcher splits names into whole words and is tested). It returns {money_columns: [{area, table, column, type, label, suggested_unit}]}: numeric columns named like money (amount/price/revenue/discount/… or a currency word such as _usd), minus rate/count/id/score and non-money unit words (minutes, hours, weight, points, units), skipping any that already have a unit. suggested_unit is what the name spells out (revenue_usd_millions → USD_millions, cost_usd_per_day → USD/day), or null. Ask once about the columns with a null suggestion, naming each by its label, never as table.column (question-cards rule 3b): one column, "What currency is the Price column on Widgets in?"; several, list their labels in the chat and ask "What currency are these 5 money columns in?" Options: the three likeliest of USD/EUR/GBP/INR/JPY (the database's region and the column names are the clue), and Mixed currencies (no unit is set); "Other" takes any other currency code. Then apply with one tested command — never pipe suggest-units through a hand-rolled script (that glue breaks, e.g. on empty stdin). Without --yes it only prints the plan:bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" set-units "<root>" --currency INR
It prints {planned: [{area, table, column, label, unit}]} and writes nothing.
When 0a.0's Source answer named a currency ($CURRENCY_HINT), it is the --currency the plan proposes. Show that plan to the user (each entry's label → unit, one line each) and apply only what they agree to: all of it with --yes, or a subset with the same --currency/--unit plus --columns <table.col …> (which writes exactly those columns, each with the unit the plan showed for it: a name that states its currency keeps that unit, the rest get --currency/--unit). A column whose name states its currency gets that unit in the plan; the rest get --currency. The write is one validated curate batch. The runtime + chart renderer format the symbol + grouping deterministically from unit (semantic_model/units.py) — no prose caveat to re-interpret. Mixed → skip (leave unit unset), one-liner. Non-currency units (cents/percent/days) → --unit <name>.
Unit grammar: <ISO code>[_<scale>][/<period>]. Scale (values stored in thousands/millions/…): thousands, millions, billions, lakhs, crores — USD_millions renders 12.5 as $12.5M. Period (a rate): hour, day, week, month, quarter, year — USD/day renders 120 as $120.00/day; both combine (USD_millions/year). Use a scale only when the column or the user says the values are stored that way; never rescale data to fit one. Anything else (kg, days) is shown as a plain label.
date_format (epoch_s/ms/us/ns, yyyymmdd, iso8601) + timezone on date-named columns whose sample values fit the shape, and iso8601 on a text column with any name when at least 20 sampled values are present and every one is a real ISO date or timestamp (a single version string, impossible date or note rules it out), so epoch integers render as human dates (UTC) deterministically. You don't ask. Do glance at the result: if a time column was missed or mis-scaled (e.g. an epoch_ms tagged epoch_s), fix it with a field:date_format/field:timezone edit op in the same batch; mention any epoch columns found in the Phase 7 summary.Write all of these with sm curate edit ops — never hand-edit tables/*.yaml or script a loop over them. One ops array, one call (validated + committed + reverted on failure):
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" curate "<root>" --ops-file "<artifacts_dir>/local/tmp/agami-caveats.json"
[{"op":"edit","kind":"table","area":"main","name":"orders","field":"caveats","value":["Order total can be negative on refunds."]},
{"op":"edit","kind":"table","area":"main","name":"orders","field":"default_filters","value":["{alias}.deleted_at IS NULL"]},
{"op":"edit","kind":"table","area":"main","name":"orders","field":"recommended_filters","value":["order_date"]},
{"op":"edit","kind":"table","area":"main","name":"events","column":"ts","field":"value_transform","value":"TO_TIMESTAMP(ts)"}]
Refreshing an existing model is the engine's job, not yours — never rebuild it and merge enrichment back by hand. When the user says the database changed ("new columns were added", "reload the schema", "refresh <table>"), run introspection with --append on the existing profile, naming only the tables that changed when they say which (--tables schema.table …). When they don't say, first find out whether the database has new tables: --tables is an allowlist, so passing only the model's own tables can never turn one up. Run sm discover for the model's schemas, compare its table list with the tables already in the model, and if there are new ones ask (multi-select) which to include; then pass the model's tables plus the chosen ones:
--dry-run. The report lists new tables: and changed <table>: added …; dropped …; retyped …; placeholders … and writes nothing. Show that list to the user in plain words and ask before writing. If it lists nothing, say the model already matches the database and stop.--dry-run, then validate.What the engine guarantees, so you don't re-do it: an existing table keeps every description, flag, caveat, sign-off and placeholder answer (a placeholder value the person already answered is not listed again; an unanswered one that is still there stays listed); a new column arrives with no enrichment; a column the database dropped is kept and marked stale (never deleted — the person decides); a changed type is updated in place. Subject areas, their descriptions, entities, metrics and existing joins are untouched — except a confirmed join on a column whose type changed, which goes back to review (joins to review in the preview: tell the user they need re-approving in /agami-model); a join introspection approved itself whose label the database's primary and unique keys now settle differently, which is relabelled (joins corrected from the database's constraints in the preview: tell the user which joins changed; a join a person signed off or edited is never changed); and single-column joins introspection approved for one foreign key over several columns, which are replaced by one join on all its columns (joins merged into one composite join in the preview; tell the user). When a person signed off or edited one of those split joins, nothing changes for that key (composite foreign key not applied in the preview: tell the user to replace them in /agami-model with one join on every column of the key). A new table goes in the area named for its schema (or the only area), and you tell the user where it went. Afterwards, describe only the new columns (2b's skip-already-described rule does this), using the model spec's Columns sheet when one was attached. Never rm, move aside or rebuild the profile to refresh it.
datasource.md is the human's narrative ONLY — it does not hold model facts. The factual summary (subject areas, conventions, the decoded glossary) is derived from the structured model at read time (cli org-context assembles it for the query path; the explorer shows it as a read-only field). The two homes stay separate by construction.
Only on the skip path (datasource.md missing/empty, the user gave no narrative), seed it with a short factual narrative so # About this database reads as something, not a blank. You've just enriched every table — so write a 1–2 sentence description of what this database is about, synthesised from the table/area descriptions (e.g. "Tracks an electric-vehicle battery-swap network — stations, vehicles, battery packs, the swap transactions between them, and the alerts they raise."). Write it under # About this database with the editable comment (a non-secret model file: the Write tool leaves it readable, so it needs no chmod). Keep it factual (don't invent business specifics you can't see); it's a starting draft the user edits.
If you can't summarise (no descriptions yet), fall back to the deterministic starter:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" org-draft "<root>" --out "<root>/datasource.md"
It writes a one-line factual seed, readable by others (mode 644 under the usual umask): a non-secret model file must stay readable for the deploy bundle and teammates.
If the user did write a narrative in 1.4, leave it untouched. The glossary from set-terminology (2b) needs no re-render — it's surfaced automatically by org-context. Mention in the Phase 7 summary that the glossary + summary are auto-derived and the narrative is theirs to edit.
The one-line datasource description (from 1.4 C). Act on $DATASOURCE_DESCRIPTION now, every onboard:
keep → nothing to do; the existing description stays.generate → synthesize ONE line from the subject-area and table descriptions you just wrote: what this datasource covers and the questions it answers (e.g. "Invoices, payments, products and margins — use for revenue and profitability questions."). Ground it in the model, never product memory. The line is built from database metadata, which can contain quotes, backticks or $(…), so it never goes on the command line: write it with the Write tool to <artifacts_dir>/local/tmp/agami-description.txt, then pass the file:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" set-description "<root>" --description-file "<artifacts_dir>/local/tmp/agami-description.txt"
datasource.yaml keeps whatever description it already had (re-introspection preserves it).The company draft (from 1.4 A's "Draft it from the database"). Write two or three plain sentences on what the business does, inferred only from the subject areas and table descriptions you just wrote (never from general knowledge of a company name), and apply them as 1.4 A says (sm set-org --description-file plus organization.md), with the first line of organization.md reading "Draft from the database; correct it in /agami-model.". Phase 7 shows it for correction.
With the coverage gate passed (sm coverage returned ok: true, 2a) and 2b–2f done, mark the step done and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark describe=done
Runs when 1.5's Ask me as you go was picked (alone or with others), after 2a–2f, so the descriptions are written and the build knows what it couldn't read; also when a returning person asks for it ("ask me the open questions"). Otherwise leave it out, with its step marked skipped (1.5). When it runs, mark its step started and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark open_questions=in_progress
Every way out of 2g to Phase 3 (the answers recorded, the data settling everything, the person skipping the rest, or the identity card's Don't sign anything yet) first marks it done:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark open_questions=done
The person is asked only what the data can't answer, in plain English, on cards; a document is asked for only for what only a person knows (1.5 did that). Say what happens first, in one line, with no duration: "Checking a few things in the data that could be read two ways, one query per table." Then:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" open-questions "<root>" --profile <profile>
It is read-only: each check is an aggregate over one table through execute_sql's gates (one statement per table, one more for its dates, two for a fiscal-year check), and never a column flagged personal. A table whose estimated size is above introspection's guard is read on its recent rows only (listed under windowed, with the day it reads from); one with no date to narrow it by is not read, and is listed under skipped with every other table not checked and why. It prints {questions, counts, failed, dropped, skipped, windowed, tables_probed, statements}. Every kind: ambiguity question has been checked on the data: the command ran each reading (counted by each date, summed each amount, counted each status set) and kept the question only when the answers differ; the ones whose readings agree are under dropped with the reason, and are never asked. The other kinds are what the build already knows it couldn't read: coded_values (codes whose meanings enrichment left blank), unknown_column (a column marked unreadable in 2a) and look_alike (two tables named alike, orders and orders_old). questions holds every one: the fiscal_start question first when the fiscal start was never asked, then ambiguities, the widest-apart first; there is no cap, so ask them on cards 4 at a time, or on the page (below). Each question names the rows in plain words (from the model's entities) and uses the business word ("completed", "open", "last month"), never a table name or a word that names one reading; pass it as written.
Post one progress line from its output: ✓ Checked <tables_probed> tables (<statements> queries): <counts.ambiguities> things the data reads two ways, <counts.coded_values> code lists and <counts.unknown_columns> columns I couldn't read. When counts.failed is not 0, say so on the next line, before anything else: "<counts.failed> tables couldn't be checked: " (the reason of the entries in failed: the error's kind, such as a dropped connection). A check that failed settled nothing, so never say the data settled anything while counts.failed is not 0. When skipped is not empty, say so on the next line too: "Not checked:
windowed is not empty, add "Large tables were checked on their recent rows: questions is empty and nothing failed, say "The data settled everything I checked." and go to Phase 3; when questions is empty and checks failed, offer to run it again once the connection works, and go on.
Cards or a page. Ask one question (header Answer how), " things to answer. Answer them on a page, or here on cards?", where <N> is len(questions): Review on a page (every item on one page that saves itself: the questions, the code lists and the unclear columns, with the build's guesses to confirm) / Answer on cards (all of them here, four at a time). With more than 8 items, mark Review on a page (Recommended) and put it first; with 8 or fewer, mark Answer on cards (Recommended) and put it first. In a remote or SSH session (SSH_CONNECTION is set) the page can't open, so leave this question out and go to the cards (question-cards rule 6a, step 1). Review on a page → the page below (Review on a page (#676)); Answer on cards → the cards.
Show each page before its card (question-cards rule 3): just before each card of up to 4 questions, a table # | Question | What the data shows with one row per question on that card, its question and its evidence (a code or column question has no evidence: leave the cell empty), so no card asks anything whose evidence wasn't shown first. Say once, before the first page, how many questions there are in all.
Then the cards: each question's card, passed to AskUserQuestion unchanged, up to 4 questions per card, in order. The command builds every card within question-cards.md's limits, so don't reword its question, rename its header, or add, drop or reorder an option: a live run that wrote its own cards dropped Skip the rest and invented a reading the data never showed. What the cards hold, so you can act on the answers: no option is marked Recommended (which date a word means is a fact only the person knows); every question ends with Skip the rest, so the list can be ended in one press, like Approve all remaining on the sign-off cards; an ambiguity offers its first two readings and Ask each time (a third reading, listed in that option's preview, is picked by typing its label in "Other"); a look_alike offers its two tables and Both are in use; coded_values and unknown_column take the meaning typed in "Other", with Not sure. Two are facts with one answer, so they offer values and no way of behaving: an ambiguity with pattern: unit (the same amount in two currencies or units) offers each unit and no Ask each time; a fiscal_start (no fiscal start was given in 1.4) offers months, any other typed in "Other".
Recording the answers: as the person's, with who and when. Before the first write, take reviewer_email and reviewer_role from <artifacts_dir>/local/.config; when either is missing, ask Phase 4's identity card (its email and role questions, saved under the same keys), which Phase 4 then doesn't ask again. Don't sign anything yet on that card writes nothing: say the answers weren't recorded, that the same questions come back the next time this step runs, and go to Phase 3. curate refuses an ambiguity signed by anyone but the reviewer_email that .config records. After each card, write its answers in one sm curate batch with --signer "<reviewer_email>" --role "<reviewer_role>": the curation log records each answer with the signer, the role and the time (sm history "<root>" shows them), and the model holds only what the person said, never your reading of the data in their name. Only an answer the person gave on a card is written with --signer, and only under an email they typed (on Phase 4's identity card, now or earlier) or that .config already holds: never one taken from git, the environment, the Claude login or memory, and never a meaning you worked out yourself. A code list you can decode from the data (country codes, say) is 2a's job: write it there with source: ai and no signer, then run open-questions again so it isn't asked; a live run that filled one in and signed it in an invented name is why this rule exists. Each question carries the op its answer completes; never write one by hand:
| answer | op |
|---|---|
a reading of an ambiguity | its op with "default": "<that option's label>" (the agent answers with it and offers the others) |
| Ask each time | its op with "behaviour": "ask" (no default) |
a unit of a pattern: unit question | that option's ops: each column's unit, and a caveat on the table naming the one people report in (a fact; no ambiguity is declared) |
a month for fiscal_start | sm set-fiscal-year "<root>" --month <1-12> (January too), not a curate op |
a table of a look_alike | that entry's ops (a caveat on the other table, saying which holds the current data) |
meanings typed for coded_values | its op, with each named code's label filled into value (the codes not named keep their blank label) |
words typed for an unknown_column | its op, with the words as value (it is stamped source: human) |
| Both are in use, Not sure | nothing |
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" curate "<root>" --ops-file "<artifacts_dir>/local/tmp/agami-answers.json" --signer "<reviewer_email>" --role "<reviewer_role>"
Skip the rest applies the card's other answers and asks nothing more; say how many were left, and that they come back the next time the schema is reloaded. "Other" on an ambiguity that names one of its options is that option; one that says the word isn't ambiguous here ("it's always the paid date") is that option too. A code typed for coded_values that isn't one of its values, or words you can't place, are re-asked, never guessed: say in one line what didn't match and ask the same card again; a question ("which one do the reports use?") is answered first, then the same card asked again (question-cards rule 5a). curate's skipped (an ambiguity already declared, say) is said back in one line.
When an answer changes a metric proposed in 2c (people mean the total with tax, and the metric sums the subtotal), say which metric in one line; it is fixed on its sign-off card in Phase 4, where "Other" takes the change. Then post: ✓ Recorded <k> answers as yours: <a> questions with two readings, <c> code lists, <d> column descriptions., every number from curate's applied.
Review on a page (#676). The same saving page as the other sign-offs (question-cards rule 6a): one row per item under a stable id, ordered by how much it changes answers. Its answers are recorded as the person's, so take reviewer_email / reviewer_role from .config first and, when either is missing, ask Phase 4's identity card before rendering (Don't sign anything yet there → the cards, which write nothing either). A fiscal_start question has no row on the page: when the list holds one, ask its card first and record it as the table above says. Then list every item and render and serve the page with the helper waiting for its save, giving the person the URL; <batch> is the stamp sm batch-id prints, and each line is its own call:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" open-questions "<root>" --profile <profile> --all --out "<artifacts_dir>/local/tmp/agami-open-questions-<batch>.json"
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" render_open_questions_page.py --items-file "<artifacts_dir>/local/tmp/agami-open-questions-<batch>.json" --profile <profile> --save-to-helper --artifacts-dir "<artifacts_dir>" --out "<artifacts_dir>/local/tmp/agami-questions-<batch>.html"
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" serve_page.py "<artifacts_dir>/local/tmp/agami-questions-<batch>.html" --decisions "<artifacts_dir>/local/tmp/agami-page-<batch>.json" --minutes 30
Run serve_page.py with run_in_background and wait as rule 6a says. Print the link in your reply, with when it expires, before the card (rule 6a step 4). --all runs the same checks, with no cards (but the fiscal start's), adds the build's own guesses (a code list it filled in alone, an opaque column it described alone, never one a person signed) and reads up to five sample values of each unclear column (never a column flagged personal). What each row offers:
pattern: unit question offers its units and Don't know only, and writes the picked unit's ops); a look-alike pair offers its two tables, Both are in use and Don't know;Blank is undecided, never a default: a row left blank writes nothing and comes back next time. The Page card is I've saved it / Back to the cards, and Back to the cards reads the helper's output before stopping it, then goes to the cards. {"status": "expired"} → "The page expired before it was saved; nothing changed.", then the Answer how card again.
What the page saved. Never read it by hand: check it against the items file the page was rendered from, which writes the batch:
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" parse_open_questions_decisions.py --decisions-file "<artifacts_dir>/local/tmp/agami-page-<batch>.json" --items-file "<artifacts_dir>/local/tmp/agami-open-questions-<batch>.json" --expect-profile <profile> --artifacts-dir "<artifacts_dir>" --ops-out "<artifacts_dir>/local/tmp/agami-answers.json"
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" curate "<root>" --ops-file "<artifacts_dir>/local/tmp/agami-answers.json" --signer "<reviewer_email>" --role "<reviewer_role>"
Each op is the one the item carries, as on the cards: a reading is its op with that default, Ask each time its op with "behaviour": "ask", a table its ops, a confirmed code list its labels as they are, a fixed one the labels typed, a confirmed column its description marked ai_validated, a fixed one the words typed (source: human), and Hide this column an exclude op; Don't know and Both are in use write nothing. {"ok": false, "error"} (exit 2: another page or model, no saved identity, a malformed file): say the error in one line, apply nothing, and ask the Answer how card again. Each of refused (an id not on the page, a choice its row doesn't offer, a fix with no words) is said back and not applied. Then say in one line what was recorded and for whom, from curate's applied and the parser's counts: "Recorded 14 answers as yours (<reviewer_email>): 6 questions, 5 code lists, 3 columns (1 hidden). 31 left blank come back next time.", list curate's skipped, delete the decisions file, the page and agami-open-questions-<batch>.json (it holds sample values), and go to Phase 3.
Mark the step started and refresh the task list (shared/task-list.md); the areas and the sign-off below are one step on the list:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark signoff=in_progress
The engine proposes the split (one area for small DBs; for large single-schema ones, tables grouped where they join each other most densely — no target number of areas, none past the size limit, a hub table doesn't pull everything into one area — with tables that have no joins grouped by their whole first name word; each table owned once, cross-area joins as cross_subject_area_relationships). Area names keep the table's plural (suppliers, status). For a multi-area split, surface it for the user to adjust — boundaries are a curation decision, not a fact:
I split <N> tables into <A> subject areas:
• <area1> — <t1, t2, …>
• <area2> — <…>
<C> joins span areas (kept as cross-area relationships).
Show the split as above (at most 15 areas; say how many more), then one AskUserQuestion (header Areas): Looks good (Recommended) / Show me the areas / Adjust, with "Other" taking the change in the person's words ("move refunds to payments"). The card can cover the list in the chat, so Show me the areas is always there: on it, print every area with all its tables (no 15-area cut), then ask the same card again. Skip silently for a single-area small DB. A change that names an area or table the model doesn't have is said back and the same card asked again; never guess which one they meant.
If they adjust, move tables with the curate move op — never by editing the subject_areas/ tree: {"op":"move","kind":"table","area":"<from>","name":"<table>","to_area":"<to>"} (add "schema" when two schemas share the table name; a to_area the model doesn't have yet is created). Its joins follow it — a join that now spans two areas becomes a cross-area join and the reverse — and metrics and entities move with it once every table they read is in the new area; the result's notes list what it moved and what stayed because it also reads another table. The whole batch is validated and undone on failure (sizing warns at 25 tables, errors at 30).
Replace each area's auto-proposed description with a real one — the engine seeds "Auto-proposed subject area covering: <tables>", which is boilerplate, but the subject-area description is load-bearing: it's what the MCP shows in its first pass so the LLM can ROUTE a question to the right area (get_datasource_schema returns name + description per area). A blank/boilerplate description means the router is guessing. So write one business line per area — what domain it covers and when you'd query it — grounded in its tables/columns (NOT product memory). Apply through the validated path, one batch (no generator script):
# one {op:edit, kind:subject_area, area:<name>, name:<name>, field:description, value:"<line>"} per area
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" curate "<root>" --ops-file "<artifacts_dir>/local/tmp/agami-area-desc.json"
Seeds reference columns, tables, metrics, and entities — so settle those before generating examples (a seed that uses a column you'd later exclude breaks at query time, and a seed built on an unreviewed metric bakes in a guessed definition). Relationships are NOT gated here — they stay lazy: FK joins are already auto-approved by the engine (the DB declared them), and inferred joins self-approve as you query, and an unreviewed one raises the trust banner on the answer's report. So you're not asked to rubber-stamp database-declared foreign keys.
4a — What needs a decision, asked on cards. One call returns the counts (turn-boundary-safe — same answer on a fresh run or a resume):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" curate-gate "<root>"
→ {pii_count, preseed_count, should_open_explorer}. PII count = columns flagged sensitive still queryable (an excluded column, or any column under an excluded table, isn't counted — so once the person hides them it drops to 0). preseed count = metrics + named-filters + entities needing sign-off (relationships are NOT gated — FK joins are engine-approved, inferred joins self-approve as you query). should_open_explorer only means "something to decide": nothing opens on this path.
PII is advisory, not a seed blocker. A non-zero
pii_countis a review nudge (the person's call to hide or keep), not a gate on seed generation. Only a non-zeropreseed_count(unreviewed metrics/entities) blocksseed-examples. Don't tell the person personal data is stopping their seeds; it isn't.
Also run bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" sensitive "<root>" every time: besides the flagged columns it prints suspected and suspected_count, columns that look personal but aren't flagged (pii_count doesn't count them).
Guessed joins: one line, no card. Read them with bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" review-items "<root>" --scope rule2 and keep the items whose kind is relationship (that scope also returns entities, which the Sign-off step covers). When there are any, post: " joins were guessed from names and data; they're used as you query and flagged on the answer until confirmed. Review them any time in agami-model." With 5 or fewer, a short table under it (Join | Kind, the item's title and cardinality); more, just the line. They are not put on a card.
Dictionary references with no join: one line, no card. Run bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" dictionary-joins "<root>" --unjoined (no database read). When unjoined_count is above 0, post: " columns the data dictionary says point to another table have no join yet: <up to 5 as Table column>." The closing summary repeats it.
If pii_count, preseed_count and suspected_count are all 0 → say "Nothing to review before examples; continuing." and go to Phase 5.
Otherwise run the two steps below that apply (conventions: shared/question-cards.md). When both apply, the review question and the personal-data question can go on the same card, two questions on one AskUserQuestion call.
Sign-offs (when preseed_count > 0). Read the queue from the engine:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" review-items "<root>" --scope preseed
Each item is {kind, area, name, extra_lines:[{label,text}], bindings, review_state, …}. A metric's meaning is its extra_lines entry labelled Definition; an entity's is its maps_to (and source_signal when set). An item with changes_since_approval was signed off before and has changed since: say so on its row. Show a markdown table, Kind | Name | What it means | SQL, one short line per item taken from those fields (never a meaning you made up), at most 15 rows, then "Showing 15 of
; <P−15> more." when there are more. The SQL column is what the item maps to, so the person checks the formula and not only the words: a metric's binding for this database's engine from bindings, with its source_tables; a join's condition; an entity's maps_to column. Show it in backticks, cut at about 80 characters with … (the whole of it is answered on request, question-cards rule 5a). The list ends the turn: one line, "
definitions wait for your sign-off:" before the table, and the reply line below after it. No card follows the list: a list before a card in the same message does not reach the person (long-text.md).
The reply line: Reply "approve all", "review each" or "later", or "page" to decide them on the model explorer. Handle the reply as the choices below; words that mean one of them count as it:
changes_since_approval, and every metric has a Definition; otherwise put review each first with "(recommended)".| Answer | Do |
|---|---|
| Approve all | The identity card first if needed (below). With more than 15 items, list the ones the table above didn't show first and confirm (question-cards rule 4). Then one batch: {"op":"approve","kind":"<kind>","area":"<area>","name":"<name>","bulk":true} per item (leave area out when the item's area is null, a cross-area metric), applied with AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" curate "<root>" --ops-file "<artifacts_dir>/local/tmp/agami-signoff.json" --signer "<reviewer_email>" --role "<reviewer_role>". Say how many were signed off, from its applied, then run sm steps "<root>" and do what its then says (shared/task-list.md). |
| Review one by one | The one-by-one cards below. |
| Skip for now | Nothing is written. Go to 4b. |
| Review on a page | The full view below, then the list again, recounted, ending its turn on the reply line. |
One by one. Up to 4 items per card, one question each. header is Metric 3/9 or Entity 3/9 (at most 12 characters; drop the word when the numbers are long). The question is only the decision, with the item's plain_name from review-items: "Sign off Revenue?", "Sign off Orders to Customers by Customer ID?" (never the identifier, ela_proficiency_rate, which goes in the preview; question-cards rule 3b). The meaning and any real value go in the Approve option's description, kept apart from the title: "Sum of paid order totals, refunds excluded. 2024-25: $4.2M". The SQL goes in the Approve option's preview, the monospace pane a card shows beside a focused option, laid out over lines with a short comment on each filter (AND status = 'paid' -- paid orders), the table it reads, and, for an item that changed since its approval, what changed. Never put the SQL in the question: a card question is plain text and a long formula there is unreadable. Options:
{"op":"reject",…})."bulk": true. Answers given on the same card to the other questions still stand.After each card, apply its answers in one sm curate batch (approvals with --signer/--role), run sm steps "<root>" and do what its then says (shared/task-list.md), then ask the next card. Every approval goes through that one command with the person's identity; never mark an item approved any other way.
"Other" on an item is a change, in the person's words ("revenue should exclude cancelled orders"). Turn it into sm curate edit ops on the field the change names (calculation, bindings, description or other_names on a metric; maps_to, description or other_names on an entity), e.g. {"op":"edit","kind":"metric","area":"<area>","name":"<name>","field":"calculation","value":"<new definition>"} plus the matching bindings edit when the SQL changes, and apply them with AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" curate "<root>" --ops-file "<artifacts_dir>/local/tmp/agami-edit.json". Never hand-edit the YAML and never a generator script. Then ask about that item again, on the next card, showing its new meaning: an edit is not a sign-off.
An "Other" that asks to stop is a stop, not a change. When the words on an item card ask to stop, pause or finish later ("stop here", "I'll do the rest later", "pause") rather than change that item, apply the card's other answers, approve or change nothing more, and go to 4b's Continue / Pause card.
Any other "Other" you can't act on is re-asked, never guessed. A question ("show me the SQL", "why?") is answered first, then the same card asked again (question-cards rule 5a). An empty change, a column or table the model doesn't have, or words you can't turn into one field's new value: say in one line what didn't match, and ask the same card again. The same when sm curate returns errors or skipped for the edit: show them, and ask the same card again.
Sign-off identity: asked once, on the first approval. Before the first approve op of the run (from Approve all, Approve, or Approve all remaining), read reviewer_email and reviewer_role from <artifacts_dir>/local/.config (the keys /agami-model uses). When both are there, use them and don't ask. When either is missing, ask one card with two questions:
Email, "Which email should sign-offs be recorded under? Type it in Other below.": options Don't sign anything yet (nothing is approved; the items stay as they are and you go to 4b) and Go back (ask again the card that led here, with nothing approved). The email is typed in "Other", e.g. [email protected]; it is asked for in the question, never offered as an option, because an option like "Type it in Other" gets clicked with nothing typed (question-cards rule 5).Role, "What is your role?": options Data Lead, Engineer, Analyst; "Other" takes any other role (≤ 40 characters).The identity is typed by the person: never infer it from git config, the environment, the credentials, or the Claude login, and don't pre-fill a domain. An email that doesn't match \S+@\S+\.\S+ is said back and the same card asked again. Save them so neither this run nor /agami-model asks again: write {"email": "<email>", "role": "<role>"}, as typed, to <artifacts_dir>/local/tmp/agami-identity.json with the Write tool, then bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" set-config "<artifacts_dir>" --identity-file "<artifacts_dir>/local/tmp/agami-identity.json", which keeps every other key (the person's words never go on the command line). An error from it about the email or role is said back and the same card asked again.
When sm sensitive prints personal_data: enforced_by_warehouse, skip this question. The organisation set that its warehouse controls who sees personal data (sm set-personal-data), so the build flagged nothing; say so in one line, "Personal data: your warehouse controls who sees it, so this build flagged none of it.", and ask nothing about it. When sm sensitive's count is above 0 (flags kept from before the setting, on a reload), add it: " columns flagged before stay flagged; change them in /agami-model."
Personal-data columns (when pii_count or suspected_count > 0). From the sm sensitive output above, {count, columns:[{area, table, column, label}], suspected, suspected_count}: columns are flagged personal, suspected look personal but weren't flagged (a phone-like or birth-date-like sample, a name like ip_address). Show both in one table, Table | Columns, marking each suspected column "(suspected)", e.g. customers | email, phone, ip_address (suspected) (a table in the chat may show identifiers; the card names them in words); at most 15 rows and "and N more". Then one multiSelect question (header Personal), "Hide these from queries": "These columns are flagged as personal data, or their names or sampled values suggest it. Which should queries never read?"
Flagged and suspected columns are picked the same way:
label, Email on Customers, or IP address on Customers (suspected); the identifier (customers.email) goes in the option's description.table.column names to hide, flagged, suspected or any other column in the model.Hide the picks in one batch, {"op":"exclude","kind":"table","area":"<area>","name":"<table>","column":"<column>"} per column, with AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" curate "<root>" --ops-file "<artifacts_dir>/local/tmp/agami-hide.json", then say how many columns are hidden and how many personal-data columns stay queryable (sm sensitive's new count). Keep them queryable writes nothing; say in one line what that leaves (flagged columns still queryable, their values included). A name in "Other" that isn't a column in the model, or Keep them queryable or Review on a page picked together with anything else, is said back and the same card asked again; never guess which column was meant.
Show the full view (an option on the Sign-off and item cards and the personal-data question, labelled Review on a page there, or asked for in words). The model explorer, with every metric, entity, join and column, which saves its own decisions (question-cards rule 6a): render it the way /agami-model preseed does in its Phase 5 (render_model_explorer.py … --initial-tab review --section <metrics|entities|joins> --save-to-helper, or --initial-tab pii from the personal-data question) and serve it from localhost with the helper waiting for its save, giving the person the URL (<batch> is the stamp sm batch-id prints):
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" render_model_explorer.py --profile <profile> --artifacts-dir "<artifacts_dir>" --initial-tab review --section <metrics|entities|joins> --save-to-helper --out "<artifacts_dir>/local/tmp/agami-explorer-<batch>.html"
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" serve_page.py "<artifacts_dir>/local/tmp/agami-explorer-<batch>.html" --decisions "<artifacts_dir>/local/tmp/agami-page-<batch>.json" --minutes 30
Run it with run_in_background and wait as rule 6a says. Print the link in your reply, with when it expires, before the card (rule 6a step 4). When the page saves, apply its decisions file as /agami-model Phase 5b does (its parser, then sm curate with the saved reviewer_email / reviewer_role), say what changed in one line (its 5c), then ask the card it was picked on again with what is left, or go to 4b when nothing is. A "Generate feedback for Claude" block pasted from an older page is still accepted: apply it the same way, then continue at 4b.
4b — after the cards: recount the sign-offs with bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" review-items "<root>" --scope preseed (review-items, not review-queue, which takes no scope). If 0 → Phase 5 (the seed command runs clean). If > 0:
Continue (Recommended) (seeds run against the current state; answers warn) / Pause — I'll finish review first (stop here; resume via /agami-connect).This is the only place "continue to examples with items still unreviewed" is offered — and the only place you pass seed-examples --after-review (otherwise the preseed-review refusal is the engine telling you Phase 4 hasn't happened). Personal data left queryable does NOT block seeds — keeping a sensitive column queryable is the person's call; only unreviewed sign-offs gate the seeds.
On reintrospect with nothing flagged sensitive and nothing unreviewed, skip silently.
When the sign-off cards are finished (items left for later included, and when 4a found nothing to review; not on Pause), mark the step done and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark signoff=done
Mark the step started and refresh the task list (shared/task-list.md):
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" steps "<root>" --mark examples=in_progress
Say what happens first: "Generating NL→SQL seeds (a spread across your tables, metrics, entities, and joins — including cross-schema ones) and EXPLAIN-validating each against the live DB. I'll report each example as it's checked."
More than 12 tables: draft each area's examples in parallel. On the same condition as 2a (more than 12 tables, an Agent tool, at least two subject areas), 5a's per-area examples come from one agami-example-writer subagent per area, launched and applied as shared/parallel-work.md says; you write the cross-schema seeds. Otherwise, generate them yourself, as written below.
5a — generate (your job — the LLM step) candidate examples grounded in the model. Aim for coverage and a good spread, not a fixed count:
data_range MAX (not NOW()) so seeds don't return 0 rows on a stale dataset.bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" context "<root>" --tables <t1> <t2> … — it returns the joins touching those tables exactly as a question will be answered (area and cross-area alike), each with its role label and full condition (a current_flag = 'Y' included), so a seed writes the join the model declares. Never read the model's YAML to find joins.cross_subject_area_relationships). For the most meaningful ones, write a question a user would actually ask that spans both schemas — a fact/metric in one schema joined to the entity it references in another. Use the relationship's declared join (on: / from→to columns) and schema-qualified table names (it's one database — ordinary cross-schema SQL, fully EXPLAIN-able). Include 2–4 of these and make 1–2 genuinely complex (3+ tables across two schemas, with an aggregation + a filter) — cross-schema SQL is exactly what NL→SQL gets wrong unaided, so a worked example pays off most here. (Cross-profile / federation seeds are out of scope — those need DuckDB ATTACH; this is cross-schema within one DB.)The person's own questions come first. When 1.5 saved <artifacts_dir>/local/tmp/agami-asked-questions.txt, write one candidate per question, its question as the person wrote it and SQL from the model, before any you make up; they go through the same validation and the same Keep / Drop cards as the rest, and Phase 6's table marks them (yours). A question the model can't answer (a table that was left out, say) is not forced: list it in one line after the table with the reason.
Tag each with its tables (list all tables it touches — both schemas for a cross-area one), columns, and metrics (every model metric it computes, by name, so it is found under each; a name the model doesn't declare rejects the seed). Store a cross-area seed under its primary/driving table's area (tagged with both schemas' tables, so the ranker can surface it from either side). Write the candidates as a JSON array to <artifacts_dir>/local/tmp/agami-seeds.json — each: required question, sql; optional tables, columns, metrics.
5b+5c — validate + write in ONE packaged call. Do NOT write a script to loop EXPLAIN over the seeds and don't hand-write the YAML. seed-examples validates every candidate against the live DB (wraps each as a zero-row query — dialect-agnostic, scans nothing), writes the passing ones (appends, dedups by question, commits), and returns the rejects with their DB error. Post one progress line from its output (totals, or added and rejected for one area): "✓ Wrote examples; failed the dry run."
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" seed-examples "<root>" --profile <profile> --file "<artifacts_dir>/local/tmp/agami-seeds.json"
Write every area's seeds in this one call: give each seed an area (the subject area it is stored under) and leave out --area, or repeat --area to limit the call to those areas. A seed with no area, or one outside the call's areas, stops the call before anything is written. With exactly one --area the seeds need no area and the output is the single-area shape {added, written, committed, rejected:[{question, error}]}; with several or none it is that shape with each rejected entry labelled area, plus areas (one such result per area, labelled area) and totals (areas, added, rejected). For each rejected, optionally regenerate once and re-run with just those; don't block the flow on a few drops. Corrections later append via /agami-save-correction (same add-example path).
The command enforces Phases 2 and 4 for you. It runs two gates before writing anything:
{refused: "columns_unenriched", unenriched_tables}→ a table got no column descriptions at all (you skipped the Phase-2 column pass). Go back, run the column pass on those tables, re-run. NOT bypassable — naked columns degrade every answer.{refused: "preseed_review_pending", pending_count}→ metrics/entities the seeds depend on are still unreviewed (you skipped the review). Go back to Phase 4a and ask its Sign-off card. Bypass only via--after-review, and only on the Phase-4b path (the person has answered the Sign-off card and chose to continue with some items unreviewed). Never pass--after-reviewto force past a fresh refusal.
Run every seed with ONE packaged call — sm seed-validate — never a hand-rolled "run all the seeds" script. It executes each written seed against the live DB through execute_sql (the same path agami-query uses), so the fan-trap / chasm-trap pre-flight and the scope/PII gates always apply — a raw-connection driver could skip that safety and let a fan-out scan the whole table. It emits the examples-validation items ({n, question, sql, row_headers, row_preview, row_count, state}); a seed the pre-flight refuses or that errors comes back with its error, not a faked result:
bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" seed-validate "<root>" --profile <profile> --out "<artifacts_dir>/local/tmp/agami-examples-items.json"
Without --area it runs every area's seeds (each through execute_sql scoped to its own area, with the same per-statement limits) and prints one object: areas ({area, examples, errored} each), items (the items above, each labelled area) and totals (areas, examples, errored). Repeat --area to run only those areas. One --area prints the bare items array, as before. An area the model doesn't have is refused with error: unknown_area and the valid_areas.
(Heads-up before you run it: on a large warehouse this executes every seed for real — some may be full-scan aggregates that cost warehouse compute. It's a one-time onboarding step; say so in one line, and run it in the background on a large warehouse.)
Show what ran, then a reply line (conventions: shared/question-cards.md). No page opens on this path, and no reply block is waited for. Post one progress line from totals (or the bare array's length and its items with an error): "✓ Ran examples: <examples − errored> returned rows, failed." Then a markdown table from the items, failing ones first, at most 15 rows, then "Showing 15 of ; <n−15> more." when there are more:
| # | Question | Rows | Result |
|---|---|---|---|
| 3 | Revenue by month this year | 12 | 2024-01 $41,200 · 2024-02 $39,850 · … |
| 7 | Top 5 customers by orders | — | failed: column "cust_id" does not exist |
# is the item's n, Rows its row_count, Result the first row or two of row_preview under row_headers (already unit-formatted), or failed: and its error. A result that looks wrong though it ran (a ratio far outside its range, a count of 0, a trend sorted by name) goes in one sentence under the table: that is 6a's case.
The table ends the turn with the reply line (a card after it in the same message would lose it, long-text.md): Reply "page" (recommended), "review each", "add my own" or "keep all". Handle the reply as the choices below; words that mean one of them count as it:
The order is fixed. Put Review one by one first and recommend it instead of the page only when the page can't open (question-cards rule 6a, step 1). A result that ran but looks wrong goes in one sentence under the table either way (6a).
Add my own is in the reply line every time, so the person's own examples are offered at the step where examples are reviewed, not only up front: the person's own examples, a .sql file or a folder of them, a sheet of questions and SQL, a dashboard export (Tableau, Power BI, LookML) or a screenshot, each checked before it is added (shared/own-examples.md); then the table and reply line again.
Dropping the failures has no option of its own: Review one by one shows them first and the page can drop them, and "drop the failing ones" typed in Other still does it (the Drop the failing ones row below).
| Answer | Do |
|---|---|
| Keep all | First, every example the table above didn't show is listed and confirmed (question-cards rule 4): a sign-off is never recorded for an example the person hasn't seen. Then the identity card from Phase 4a if reviewer_email/reviewer_role aren't saved yet; here Don't sign anything yet leaves every example written but unsigned and goes on to Phase 7 (not 4b). Then, per area, write the examples that ran back with their own question and sql (same SQL, so it is a sign-off, not a change; their tags are kept): AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" add-example "<root>" --area <area> --file "<artifacts_dir>/local/tmp/agami-keep-examples.json" --signer "<reviewer_email>" --role "<reviewer_role>". The sign-off is recorded in curation_log.jsonl, not on the example. Failed ones are left as they are; say how many. |
| Drop the failing ones | Write each failed item as one <area>/<question> line, the question exactly as saved, to <artifacts_dir>/local/tmp/agami-reject.txt with the Write tool, then bash "${CLAUDE_PLUGIN_ROOT}/scripts/sm" remove-example "<root>" --question-file "<artifacts_dir>/local/tmp/agami-reject.txt" (--signer/--role when known). They are marked rejected and kept for audit, not deleted: say so. |
| Review one by one | The one-by-one cards over every item, failed ones first; Keep all remaining on each card ends the review once the failures are dealt with. |
| Add my own | shared/own-examples.md, from its step 1; it checks each statement through /agami-reconcile, adds the ones that agree as examples signed as the person's, and asks about the ones that disagree. Its run is separate from the seeds, so nothing on this card is decided by it. Then this card again for the seeds. |
| Mark them on a page | The full view below. |
One by one. Ask up to 4 examples per card, one question each, header Example 3/9 (at most 12 characters; past 9/99 use Ex 12/40). The question is the example's question and what it returned, "Revenue by month this year: 12 rows, 2024-01 $41,200" (or "failed: "). The SQL goes in the Keep option's preview, as a metric's does on its sign-off card: the item's sql, laid out over lines with a short comment on each filter, then the first rows of row_preview under row_headers (or the error for a failed one), so the person checks the statement without asking for it (question-cards rule 3a). Options: Keep (the add-example sign-off above, for that one), Drop (remove-example for that one), Keep all remaining (keep this one and every remaining one that ran), and Mark them on a page (the page below, on every question of the card; answers given on the card's other questions are applied first). "Other" describes a fix in the person's words ("should only count paid orders"): rewrite that example's SQL, write it with sm add-example (same question, so it replaces), re-run its area with sm seed-validate "<root>" --profile <profile> --area <area>, and ask about it again showing the new result. A fix that touches a column or metric beyond this one example is 6a's: fix it everywhere, as 6a says. A question ("show me the SQL", "show me the rows") is answered first, then the same card asked again (question-cards rule 5a). An "Other" you can't act on is re-asked, never guessed: an empty fix, or one naming a column the model doesn't have, is said back and you ask the same card again.
When every example has an answer, mark the step done (the examples=done mark at the end of 6a), then 6b when 1.5 saved reports, then Phase 7.
Show the full view (an option on the Examples and one-by-one cards, labelled Mark them on a page there, or asked for in words). The examples-validation page, with every result and its SQL, which saves its own decisions (question-cards rule 6a): Keep, Reject (drop), Edit (a fixed SQL) or a note on each example, and a note for the whole model. When reviewer_email / reviewer_role aren't saved yet, the identity card from Phase 4a first: kept examples are signed as that saved identity, which the page shows. Render it from the items and serve it from localhost with the helper waiting for its save, giving the person the URL; <batch> is the stamp sm batch-id prints, and each line is its own call:
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" render_examples_validation.py --title "Seed examples · <profile>" --profile <profile> --items-file "<artifacts_dir>/local/tmp/agami-examples-items.json" --save-to-helper --artifacts-dir "<artifacts_dir>" --out "<artifacts_dir>/local/tmp/agami-examples-<batch>.html"
AGAMI_SCRATCH_ONLY=1 bash "${CLAUDE_PLUGIN_ROOT}/scripts/py" serve_page.py "<artifacts_dir>/local/tmp/agami-examples-<batch>.html" --decisions "<artifacts_dir>/local/tmp/agami-page-<batch>.json" --minutes 30
Run serve_page.py with run_in_background and wait as rule 6a says. Print the link in your reply, with when it expires, before the card (rule 6a step 4). Its Page card's options are I've marked them on the page and Back to the cards; the saved page tells the person to press the first, and Back to the cards reads the helper's output b
What SKILL.md sets; muted values are Claude Code's defaults
Run when the user installs the plugin for the first time, asks 'how do I set up agami' / 'connect to my database' / 'introspect my database' / 'introspect the schema' / 'reload schema' / 'add a new database', wants to try agami WITHOUT a database ('I don't have a database', 'try the sample', 'use the sample data', 'demo data'), or after the user changes their schema and wants the model refreshed. Also auto-invoked by agami-query the first time it runs (when the semantic model is missing). This skill handles credential setup, introspection, enrichment, and seed-example validation — one entry point for everything before the user can query. The sample-database path (Phase 0s) needs no connection and copies in a ready, queryable model.
npx claudepluginhub agamiai/agami-core --plugin agami-core9 skills in this plugin
/agami-deployEARLY ACCESS (in testing) — usable today, but newer than the local single-player path; feedback welcome via a GitHub issue. Prepares a ready-to-run, self-hosted agami deploy bundle ON THE USER'S MACHINE so a team can stand up a shareable MCP server their Claude connects to. Conversationally gathers the hard-floor inputs (hostname, admin identity), auto-detects the local model, writes docker-compose.yml + Caddyfile + a filled agami.env (referencing the PUBLISHED image ghcr.io/agamiai/agami-core — no clone, no build), and stages the model artifacts. Generates the signing secret via deploy_preflight; the admin password is typed by the user into the file (never in chat). Then runs `docker compose up` if Docker is local, otherwise prints the exact VM steps + the shareable MCP URL. Username/password auth only on this paved path./agami-evalRuns the golden evaluation harness for a profile. Picks one golden dataset, regenerates SQL for every question in it, executes each statement against the org's own warehouse, scores the result against the confirmed answer key, and reports the verdicts — failures first, with the errored, the unscored and the unconfirmed each kept separate. Scoring is deterministic and happens in agami-core; the skill reports it and never re-judges it. Neither the answer key nor the generated statement is printed: both stay in a local JSON artifact the report points at./agami-modelThe semantic model in the chat: what needs sign-off and the subject areas with their tables, then a card — review what needs sign-off (approve / reject the AI-proposed metrics, entities and guessed joins; Rule 1 — a query using an unsigned metric still answers but carries a warning until it's approved), hide tables or columns from queries, look up a table or metric, or show the full view (the model explorer page: browse with live search, edit descriptions/metrics/entities/joins, add metrics, edit datasource.md). Every change is applied through the curation engine and gated by the validator before it touches the YAML. (This skill absorbed the former `/agami-review`.)/agami-queryAnswers natural-language questions about the user's database. Loads the agami semantic model (subject areas, tables, columns, relationships with join cardinality, entities, metrics) and few-shot examples from <artifacts_dir>/<profile>/, generates SQL via the examples-first traversal (pick subject area → match examples → resolve entities/metrics → compound table context), executes it locally via the user's chosen tool (psql / mysql / snowsql / sqlite3 native CLI, DuckDB binary, or the Python driver `execute_sql.py` — which runs the scope gates and reports fan-trap/chasm-trap and aggregation findings on the receipt), returns results as a markdown table with optional CSV export, and renders Chart.js HTML charts on request. All execution is local — no data leaves the machine./agami-reconcileReconciles known (label, expected_value) numbers from an existing dashboard against agami's answers. Input can be a SCREENSHOT of a Metabase / Power BI / Tableau / Looker dashboard (Claude's vision extracts the pairs), a CSV, or numbers pasted inline — the user doesn't need to know which; they can just ask. For each pair, the skill generates a matching NL question, runs it through the active profile's semantic model, diffs actual vs expected, and surfaces matches in green and mismatches in red with drill-down receipts. The strongest onboarding demo for a skeptical data engineer — either we agree with their numbers (trust earned via evidence) or we surface a real definitional disagreement (trust earned via transparency)./agami-save-correctionSaves a user correction so future queries learn from it. Always appends a (question, corrected_sql) pair to the subject area's example library under <artifacts_dir>/<profile>/prompt_examples/<area>/. Additionally, classifies the correction and — when applicable — applies a surgical edit to the semantic model itself (relationship fix, column metadata, or new metric) via the curation engine. Every model edit is validated before write; the validator is the binding gate, and a failed validation reverts. Shows the user a model diff for approval before any model mutation.Other plugins' skills for the same job