Metadata-Version: 2.4
Name: sarkoa
Version: 0.4.4
Summary: Sarkoa CLI — upload, list, download, and manage geospatial assets on Sarkoa
Author-email: Sarkoa <support@sarkoa.com>
License-Expression: GPL-2.0-or-later
Project-URL: Homepage, https://sarkoa.com/en-CA/downloads
Project-URL: Documentation, https://sarkoa.com/en-CA/docs/cli
Project-URL: Repository, https://gitlab.com/sarkoa/plugins
Project-URL: Issues, https://gitlab.com/sarkoa/plugins/-/issues
Keywords: sarkoa,geospatial,gis,cli,qgis
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: GIS
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# Sarkoa (`sarkoa`)

**Sarkoa CLI**, **QGIS plugin**, **ArcGIS Pro toolbox**, and **MCP server** for uploading, listing, viewing, downloading, and managing files on the Sarkoa platform.

## Install the CLI (public)

```bash
# curl (recommended) — inspect first if you prefer
curl -fsSL https://packages.sarkoa.com/install.sh | bash

# or pipx from the CDN wheel (resolve LATEST; do not use sarkoa-latest.whl directly)
pipx install "https://packages.sarkoa.com/wheels/$(curl -fsSL https://packages.sarkoa.com/wheels/LATEST)"

# Coming later: pipx install sarkoa (PyPI) / apt — see https://sarkoa.com/en-CA/downloads
sarkoa --help
```

## Install the QGIS plugin (public)

- ZIP: [plugins.sarkoa.com/qgis/sarkoa-qgis-latest.zip](https://plugins.sarkoa.com/qgis/sarkoa-qgis-latest.zip) (also `sarkoa-qgis-<major>-<minor>-<patch>.zip`)
- Plugin Manager: search **Sarkoa** on [plugins.qgis.org](https://plugins.qgis.org) (when listed)

Marketing landing page: [sarkoa.com/downloads](https://sarkoa.com/en-CA/downloads).

### QGIS 0.4.3: coordinate systems and saved connections

QGIS plugin 0.4.3 preserves the source coordinate system when converting a DXF into
the local GeoPackage used by QGIS. It uses source CRS metadata when provided by Sarkoa,
or remembers the CRS selected during upload for that source generation. For an older DXF
with no available CRS, Add to Map asks for its Earth EPSG coordinate system before import.
Assigning this CRS does not transform the drawing's numeric coordinates. Replacing the
source invalidates its remembered CRS, preventing a previous drawing's CRS being reused.

On Windows, Connection offers **Protect this key with Windows sign-in (no QGIS master
password)**. This stores the key in Windows Credential Manager for the current Windows
user and QGIS profile. It does not reset QGIS authentication or alter other saved
connections. A forgotten QGIS master password still protects keys in that older store;
reconnecting requires an existing authorized Sarkoa API key. Keys are never written to
plain-text QGIS settings. Other operating systems retain QGIS's encrypted authentication
store. If secure storage is unavailable, a new key works only for the current session
and the dialog reports that it was not saved.

Release notes and verification: [QGIS 0.4.3](docs/releases/qgis-0.4.3.md).

**Public release (maintainers):** [RELEASE_GATE.md](RELEASE_GATE.md) — early CDN cut (R2 wheel + ZIP + install.sh) first; PyPI / apt / plugins.qgis.org when verifications land.

**Live CLI functional QC** (needs an API key):

```bash
export SARKOA_API_TOKEN='…'   # Profile → API & Integrations
./scripts/qc-cli.sh             # build wheel → temp venv → whoami/list/upload/download/delete
# apt-like:  ./scripts/qc-cli.sh --deb-docker
# faster:    ./scripts/qc-cli.sh --editable
# series:    ./scripts/qc-cli.sh --with-series
```

Both `qc-cli.sh` and `qc-plugin-core.sh` sweep the org for `qc-*` leftovers on start and exit
(files + series with entries). To clean without a full QC run:

```bash
./scripts/qc-cleanup.sh              # delete qc-* artifacts now
./scripts/qc-cleanup.sh --dry-run    # list what would be removed
```

**Live bundled plugin-core QC** (same API surface, no QGIS/ArcGIS install):

```bash
export SARKOA_API_TOKEN='…'
./scripts/qc-plugin-core.sh              # sync-core → HttpSarkoaClient from qgis/arcgis/mcp bundles
./scripts/qc-plugin-core.sh --bundle qgis
./scripts/qc-plugin-core.sh --with-series
# pytest equivalent (skipped unless both env vars set):
SARKOA_LIVE_QC=1 pytest -m live
```

---

# Developer notes

This repository also contains the ArcGIS Pro toolbox and MCP server. Desktop plugins and the MCP server share **`sarkoa_core`** (HTTP client + optional local mock for tests). QGIS/ArcGIS bundle a copy of `sarkoa_core` via `scripts/sync-core.sh`.

**Requirements:** Python **3.10+** (`pyproject.toml`). QGIS **3.40+** (including QGIS 4) for the QGIS plugin.

## Project layout

```
plugins/
  src/
    sarkoa_core/          # Shared storage client library
    sarkoa_cli/
      main.py             # CLI entry point
  qgis_plugin/
    sarkoa_plugin/
  scripts/                # build / smoke / publish (gated)
  packaging/nfpm.yaml
  tests/
  pyproject.toml
  LICENSE                 # GPL-2.0
  RELEASE_GATE.md
```

## Backends (development)

| Backend | When to use |
|---------|-------------|
| `http` | Real API usage — set `base_url` and `api_token` |
| `mock` | Offline unit tests — local files under a mock root |

Public installs should use the HTTP backend with an API key from the web app.

## Configuration

Settings resolve in this order (first wins):

1. `--token TOKEN` CLI flag (one-shot, implies `backend=http`, not stored)
2. `SARKOA_*` environment variables
3. `~/.sarkoa/config` JSON file (written by `sarkoa config set`)
4. Defaults

### Environment variables

| Variable | Purpose |
|----------|---------|
| `SARKOA_BACKEND` | `http` (default when a token is set) or `mock` |
| `SARKOA_API_TOKEN` | API key from the Sarkoa web app (Profile → API & Integrations) |
| `SARKOA_ORGANIZATION_ID` | Optional org UUID |
| `SARKOA_USER_AGENT` | Override HTTP `User-Agent` (default: `SarkoaCLI/<version>`) |
| `SARKOA_CLI_BYPASS_KEY` | Shared secret sent as `X-Sarkoa-Cli-Key` when prod WAF requires it (set via `sarkoa config set cli-bypass-key …` or env) |
| `SARKOA_BASE_URL` | **Dev/QC only.** App origin override (defaults to the public Sarkoa app). Prefer env over `config set base-url`. |

The default User-Agent begins with `SarkoaCLI/` so Cloudflare WAF can allowlist the CLI for `/api/*`. When `cli_bypass_secret` is configured in prod Terraform, the same value must be set here (or in `~/.config/sarkoa/config.json` as `cli_bypass_key`).

---

## Install from source (contributors)

```bash
python -m venv .venv
source .venv/bin/activate
pip install -e .
sarkoa --help
```

### Configure credentials (HTTP backend)

```bash
sarkoa config set token MY_API_TOKEN
sarkoa config set org-id MY_ORG_UUID   # optional
sarkoa config show
```

The CLI uses the public Sarkoa app by default. For a non-production stack only:

```bash
export SARKOA_BASE_URL="https://dev-app.sarkoa.com"   # development / QC
export SARKOA_API_TOKEN="MY_API_TOKEN"
```

Or pass a one-time token without storing anything:

```bash
sarkoa --token MY_API_TOKEN list
```

### Check connection

```bash
sarkoa whoami
```

Prints the authenticated user's details (HTTP backend) or the mock root path (mock backend).

### Upload

```bash
sarkoa upload /path/to/file.geojson
sarkoa upload /path/to/file.geojson --folder Surveys
```

With an optional pre-built cloud-native counterpart:

```bash
sarkoa upload /path/to/source.geojson --cloud-native /path/to/source.pmtiles
```

Files under 10 MB use a presigned single-part upload; files 10 MB and larger use multipart automatically (same threshold as the web app). On a TTY, transfers at or above 10 MB show a stderr progress bar (`--progress` / `--no-progress` to force).

### List

```bash
sarkoa list              # name, type (Polygon / Polyline / Raster (N bands) / Folder), status, size, relative time, short ref
sarkoa list --json       # JSON array with full IDs, cloud format, geometry, band count
sarkoa list --search boundary   # filter by name, short ref, status, or type (e.g. polygon, raster)
sarkoa list --folder Surveys    # contents of one folder (omit --folder for the library root)
```

The default table hides full UUIDs (use the 8-character `REF`, or `status` / `--json` for the full ID). Cloud packaging labels like `pmtiles` are JSON/status-only.

### Folders

```bash
sarkoa mkdir Surveys
sarkoa mkdir 2026 --parent Surveys
sarkoa upload ./data.geojson --folder Surveys
sarkoa mv ./other.geojson Surveys
sarkoa mv abc12345 --root
sarkoa delete Surveys --yes --recursive
```

`--folder` / destination / `--parent` accept a folder name, short ref, or full ID. Moving a folder moves its contents with it. Deleting a folder that still has contents requires `--recursive` (empty folders need only `--yes`).

### Status

Show processing status and metadata for one file (full ID, human type, cloud format):

```bash
sarkoa status <file-id-or-filename>
sarkoa status <file-id-or-filename> --json
```

### Inspect

Map-authoring metadata (vector fields, raster bands, canonical metadata, rendering profiles):

```bash
sarkoa inspect <file-id-or-filename>
sarkoa inspect <file-id-or-filename> --json
```

### Raster rendering profiles

List, create, update, delete, and set the default profile for a raster asset (no reprocessing):

```bash
sarkoa raster profile list <file-ref> [--json]
sarkoa raster profile create <file-ref> --name "DEM viridis" --definition-file profile.json
sarkoa raster profile update <file-ref> <profile-id> [--name ...] [--definition-file ...] [--expected-revision N]
sarkoa raster profile delete <file-ref> <profile-id> --yes
sarkoa raster profile set-default <file-ref> <profile-id>
```

Profile definitions follow the map-core contract: `rgb` (`bands`), `continuous` (`band`, `ramp`, `vmin`, `vmax`), or `categorical` (`band`).

### Delete

```bash
sarkoa delete <file-id-or-filename> --yes
sarkoa delete Surveys --yes --recursive
```

Requires `--yes` to confirm. Folders that still have contents also need `--recursive`. Works with both backends (HTTP calls `DELETE /api/assets/{id}` with `Content-Type: application/json` so Astro origin checks accept the request; an empty JSON body is valid when optional fields such as `archive` are omitted).

### Upload rate limits

`POST /api/uploads/complete` is limited to **30 completions per 10 minutes** per API key (or signed-in user). `POST /api/uploads/presign` allows **60 per 10 minutes**. When you hit the limit, the API returns `429` with a `Retry-After` header (seconds). The CLI retries completion on `429` and waits at least that long. For large backfills, pace uploads (about one completion every 20 seconds stays under the cap) or spread work across time.

### Share (public links)

```bash
sarkoa share create <file-id-or-filename> [--access view|download|view_download] [--expires-days N] [--password SECRET] [--json]
sarkoa share list <file-id-or-filename> [--json]
sarkoa share revoke <file-id-or-filename> <share-id> --yes
```

Creates a public `/share/…` link via `POST /api/assets/{id}/shares` (`share_type=public_link`). Default access is `view`. Password-protected links require Essential+. Revoke requires `--yes`.

### Download

```bash
sarkoa download <file-id-or-filename> /tmp
```

Works with both backends. HTTP backend fetches short-lived signed source download URLs from the API. Large downloads show a progress bar on a TTY (same `--progress` / `--no-progress` flags as upload).

### View

Opens the file in a viewer. With the HTTP backend this opens the Sarkoa web app file page (`{base_url}/files/{file_ref}`). With the mock backend it resolves the local cloud-native path (e.g. `.pmtiles` or COG `.tif`) and opens it.

```bash
sarkoa view <file-id-or-filename>
```

Print the target URL/path without opening a browser:

```bash
sarkoa view <file-id-or-filename> --print-only
```

### Time series (Append-Aware Series)

Manage sequential asset containers and append new entries with an idempotent, overlap-safe reservation flow:

```bash
sarkoa series list
sarkoa series list --json
sarkoa series create "Monthly imagery" --render-mode entry_swap
sarkoa series append <series-id> tile.tif --captured-at 2026-07-01T00:00:00Z
sarkoa series append <series-id> tile.tif --captured-at 2026-07-01T00:00:00Z --period-start 2026-06-01T00:00:00Z
sarkoa series append <series-id> day.geojson --captured-at 2026-07-01T00:00:00Z --temporal-mode off
sarkoa series status <series-id> <append-request-id>
```

`--temporal-mode off` matters for **vector** entries. A vector upload otherwise
defaults to `auto`, which indexes a date column found inside the file and gives
that entry a second, feature-level timeline. The viewer then applies the map's
playhead twice — once to select the frame, once to filter the features inside it
— and a snapshot frame filters itself down to nothing. Set it to `off` unless one
entry really does span its own range of feature timestamps.

`series append` reserves an upload slot with `POST
/sequential-assets/{id}/append`, uploads the file, then completes registration
against that reservation. Files below 10 MiB use a signed PUT; files at or above
10 MiB use retryable multipart parts without buffering the whole file. If
`--idempotency-key` is omitted, one is derived deterministically from the file
path and `--captured-at` so retries of the same command are safe. HTTP backend
only (requires `ENABLE_APPEND_SERIES` on the server).

### Custom maps

Author versioned custom maps from a canonical `MapDocumentV1` JSON document. Map references accept a full ID, a unique ID prefix, or a unique title.

```bash
sarkoa map validate --file map.json
sarkoa map create --file map.json
sarkoa map list
sarkoa map export <map-id> --output map.json
sarkoa map apply --file map.json <map-id> --expected-revision 3
sarkoa map layer add <map-id> --asset roads.geojson --style-file roads-style.json
sarkoa map layer classify <map-id> <layer-id> --attribute kind
sarkoa map layer classify <map-id> <layer-id> --shuffle
sarkoa map layer hide <map-id> <layer-id>
sarkoa map display <map-id> --mode 3d --projection globe
sarkoa map access <map-id> --mode organization
sarkoa map access <map-id> --mode public --yes
sarkoa map open <map-id>
```

Use `--file -` to read a document from standard input. `map create` and `map apply` support `--dry-run`. Creating or applying a public, password-protected, or email-invite map requires `--yes`. Deletion requires `sarkoa map delete <map-id> --yes`.

### Print layouts

A print layout is a `PrintSpecV1` JSON document (paper, framing, text, legend, scale bar; every field optional, schema in `map-core/schemas/print-spec-v1.json`). No command downloads a PDF: the print composer makes it in the browser. The commands save and check layouts and print the composer link to open.

```bash
sarkoa map print-layout preview <map-id> --spec sheet.json      # check without saving (view access)
sarkoa map print-layout create <map-id> --spec sheet.json --name "A3 site plan"
sarkoa map print-layout list <map-id>                           # plan limits + saved layouts
sarkoa map print-layout get <map-id> <layout-id> --output sheet.json
sarkoa map print-layout update <map-id> <layout-id> --spec sheet.json   # replaces the spec whole
sarkoa map print-layout open <map-id> <layout-id>               # --no-browser to only print the URL
sarkoa map print-layout delete <map-id> <layout-id> --yes
```

Saving, updating, and deleting need edit access to the map; `preview` and `open --spec` need only view access. A full map UUID skips the organization map lookup, so a public map from elsewhere can be previewed.

### Public directory (Explore)

Listing a map puts it in Explore, the public directory of Sarkoa maps, and in search engines. Making a map public does not list it; listing is a separate step, and only owners, admins and editors of the organization can take it.

```bash
sarkoa map listing get <map-id>                  # status, what blocks listing, terms and guidelines links
sarkoa map listing set <map-id> --listed --category hazards --confirm-guidelines
sarkoa map listing set <map-id> --listed --category hazards --confirm-guidelines
sarkoa map listing set <map-id> --unlisted       # takes it out; the map and its link are unchanged
```

`--confirm-guidelines` is your confirmation that the map follows the community guidelines, so read them first (`get` prints the link). When `get` says the current terms are not yet accepted, accept them in Sarkoa first (open the map in the map builder and list it there once): an API key cannot accept them for a person. `--tag` (repeatable, at most five kept) overrides the map's own tags. When the map fails a check, nothing is listed: each problem prints as a `code: message` line and the command exits non-zero. A listed map appears in Explore straight away; only a map with open reports waits for a moderator.

---

## Install and use the QGIS plugin

The plugin requires **QGIS 3.40+**, including QGIS 4. It talks to the Sarkoa web app when `SARKOA_BACKEND=http`, using the settings configured in the dock or via environment variables.

### Install

**Option A — Copy folder:**

1. Copy the entire **`qgis_plugin/sarkoa_plugin`** folder (including the nested **`sarkoa_core`** directory) into your QGIS **Python plugins** folder for the active profile.
2. Restart QGIS.
3. Open **Plugins → Manage and Install Plugins → Installed**, enable **Sarkoa**.

Typical plugin directories (profile `default`):

| OS | Path |
|----|------|
| Linux | `~/.local/share/QGIS/QGIS3/profiles/default/python/plugins/` |
| macOS | `~/Library/Application Support/QGIS/QGIS3/profiles/default/python/plugins/` |
| Windows | `%APPDATA%\QGIS\QGIS3\profiles\default\python\plugins\` |

**Option B — Install from ZIP:**

1. Zip the `qgis_plugin/sarkoa_plugin` folder.
2. Open **Plugins → Manage and Install Plugins → Install from ZIP**, select the zip, click **Install Plugin**.

### Use

1. Open the Sarkoa dock from the toolbar or **Plugins → Sarkoa**.
2. For the HTTP backend: open **Settings**, enter the base URL and API token (and optional org ID), save, then click **Refresh**.
3. Use the **Filter files…** search box to narrow the list.
4. In the dock: **Upload**, **Refresh**, select a row and **View** (opens layer or web viewer) or drag to the map canvas; **Download** and **Delete** are supported for both backends.

The dock uses Sarkoa brand colors (forest green primary, terracotta accent) aligned with `@sarkoa/styling`. The file list shows a type icon (point / polyline / polygon / raster), the filename, a right-aligned size, and a right-aligned status column (UUID is tooltip-only).

**Append to a time series:** the upload picker has an "Append to time series" group, off by default. Enable it, pick or type a series ID (the combo is prefilled from the API when reachable) and a captured-at date/time, then upload as usual — the file is tagged as one entry of that series (`sequential_id` + `sequential_captured_at`).

### Optimize locally before upload (HTTP)

Removed from the QGIS dock (it depended on installing the full cloud processor into QGIS’s Python, which is not a supported path). Cloud optimization on Hetzner remains the default after source upload.

See **[docs/LOCAL_OPTIMIZATION.md](docs/LOCAL_OPTIMIZATION.md)** for why, and for the intended future architecture (shared convert library + external CLI, not processor-in-plugin).

Uploads larger than **10 GiB** are rejected client-side with a clear error.

---

## Mock backend

The mock backend stores files locally — useful for testing without a Sarkoa account.

Default location: `~/.sarkoa/mock`

Override:

```bash
export SARKOA_MOCK_ROOT="/custom/path/to/mock-store"
```

Force mock regardless of other settings:

```bash
export SARKOA_BACKEND="mock"
```

The mock index lives at `<mock_root>/index.json`. Source files go under `<mock_root>/files/` and cloud-native counterparts under `<mock_root>/cloud_native/`.

---

## Tests

```bash
pip install -e .
pytest
```

---

## Install and use the ArcGIS Pro toolbox

The toolbox requires **ArcGIS Pro 2.9+** (Python 3.9+). It uses the same
`~/.sarkoa/config` credentials as the CLI and QGIS plugin so you only configure once.

### Install

1. Open ArcGIS Pro.
2. In the **Catalog** pane, right-click **Toolboxes** → **Add Toolbox**.
3. Browse to **`arcgis_addin/sarkoa_plugin/SarkoaToolbox.pyt`** and click **OK**.

The **Sarkoa** toolbox now appears under Toolboxes with two tool categories:
**File Operations** and **Settings**.

### Configure credentials (HTTP backend)

Run the **Settings → Set Configuration** tool and fill in the API Token
(and optional Org ID). These are saved to `~/.sarkoa/config` and shared with the CLI.
The toolbox uses the public Sarkoa app by default.

Or set environment variables before launching ArcGIS Pro:

```bash
SARKOA_API_TOKEN=MY_API_TOKEN
```

For a non-production stack only, also set `SARKOA_BASE_URL` (development / QC).

### Tools

| Category | Tool | What it does |
|---|---|---|
| File Operations | **Upload File** | Upload a geospatial file; optional pre-built cloud-native (.pmtiles / COG .tif) |
| File Operations | **List Files** | Print a human file table (name, type, status, short ref); optional output to a standalone geodatabase table |
| File Operations | **Download File** | Download by file ID (or prefix) or filename to a local folder |
| File Operations | **Delete File** | Permanently delete by file ID (or prefix) or filename (requires confirmation) |
| File Operations | **Add to Map** | HTTP: opens web viewer in browser. Mock: adds cloud-native file as an ArcGIS Pro layer |
| Settings | **Who Am I** | Verify the connection; prints authenticated user info or mock root path |
| Settings | **Set Configuration** | Persist API token, Org ID, and backend to `~/.sarkoa/config` |
| Settings | **Show Configuration** | Display stored config (token masked) |
| Settings | **Clear Configuration** | Delete `~/.sarkoa/config` and revert to mock defaults |

### Tips

- Every tool has an optional **API Token** parameter (Advanced → Connection) for one-time token overrides that are not stored.
- The **List Files** output table can be connected directly to other geoprocessing tools via ModelBuilder.
- The **Download File** derived output (`Downloaded File Path`) can feed into **Add to Map** or **Add Data** in a model.

---

---

## MCP server

### Hosted (production)

AI agents should use the **hosted** Streamable HTTP endpoint (no local install):

- Prod: `https://mcp.sarkoa.com/mcp`
- Dev: `https://dev-mcp.sarkoa.com/mcp`

Authenticate with `Authorization: Bearer <API_KEY>` (same keys as the CLI). Docs: marketing `/docs/mcp`. Worker source: `infra/workers/mcp/`.

### Local stdio (`mcp/`, advanced)

The Python package under `mcp/` still exposes Sarkoa storage as MCP tools over **stdio** for developers and hosts that only spawn local processes. It bundles its own copy of `sarkoa_core` and uses `~/.sarkoa/config` / `SARKOA_API_TOKEN`.

```bash
cd mcp
python -m venv .venv
source .venv/bin/activate
pip install -e .
```

```json
{
  "mcpServers": {
    "sarkoa": {
      "command": "/path/to/mcp/.venv/bin/sarkoa-mcp",
      "env": {
        "SARKOA_API_TOKEN": "MY_API_TOKEN"
      }
    }
  }
}
```

Prefer the hosted URL for paying customers.

---

## Keeping bundled copies of sarkoa_core in sync

QGIS, ArcGIS, and MCP bundle their own copy of `sarkoa_core`. When you change `src/sarkoa_core/`, run:

```bash
./scripts/sync-core.sh
```

Or manually:

```bash
for f in config.py client_interface.py mock_client.py http_client.py models.py client_factory.py __init__.py; do
  cp src/sarkoa_core/$f qgis_plugin/sarkoa_plugin/sarkoa_core/$f
  cp src/sarkoa_core/$f arcgis_addin/sarkoa_plugin/sarkoa_core/$f
  cp src/sarkoa_core/$f mcp/sarkoa_mcp/sarkoa_core/$f
done
```
