# Field: Runtime Integration Architecture & API Evolution

**Packet:** terminal-workspace-orchestration
**Date:** 2026-05-29
**Scope:** Integration patterns between a Python CLI/daemon runtime (`ironsilk`/`tide`) and the Next.js/TypeScript web layer; monorepo package boundary design for `packages/tide`; API-evolution and deprecation discipline for the vocabulary migration (`scene`→`workspace`, codename retirement).

---

## Canonical Concepts

**Plumbing vs. porcelain** (git model): plumbing commands are low-level, stable, machine-readable; porcelain is human-facing and may change. A `--format json` flag on a CLI is a deliberate choice to make the CLI a first-class machine contract — but only if the schema is versioned and documented. Without that, stdout is fragile text.

**IPC mechanisms, ranked by overhead (local, single-host):**
Unix domain socket < named pipe < TCP loopback < HTTP/1.1 local ≈ gRPC local. UDS achieves ~130 µs vs ~334 µs for TCP loopback in Node.js benchmarks (50% lower latency). gRPC over UDS combines structured contracts with low-latency transport.

**SemVer (semver.org):** MAJOR = breaking; MINOR = additive, backward-compat; PATCH = bug fix. Deprecation sequence: (1) document in MINOR release, (2) emit warning, (3) remove in next MAJOR. Never remove without at least one release-cycle warning window.

**Stripe date-based API versioning:** clients pinned to a dated snapshot (`2026-05-27.dahlia`); server keeps all supported snapshots active; breaking changes only in named major releases (twice yearly). SDK uses SemVer for library code; API epoch for behavior. Strongly-typed SDKs (stripe-node v12+) are pinned to the API version current at SDK release time.

**Python PEP 387 deprecation:** minimum two-year window before removal; hard deprecations use `DeprecationWarning` at runtime; soft deprecations are doc-only. PEP 702 adds `@warnings.deprecated()` decorator for typed deprecations.

**Node.js release lifecycle:** six-month Current → LTS (Active 18 mo, Maintenance 12 mo) → EOL. Deprecation of APIs tracked in the official deprecation list; runtime warnings via `--pending-deprecation` flag.

**pnpm `workspace:` protocol:** internal packages referenced as `"workspace:*"`; on publish, converted to real semver. Single root lockfile. TypeScript project references (`composite: true`) enable incremental builds across package boundaries.

**protobuf field deprecation:** mark field `[deprecated = true]`; `reserved` the field number and name after removal to prevent accidental reuse; never change field numbers; add new fields rather than modify existing ones. Reserve at least 3 months of dual-support before dropping deprecated fields.

**OpenAPI as contract source of truth:** define response shapes in `.openapi.yaml`; generate TS types with `openapi-typescript` (runtime-free type generation); version the spec file under the API's SemVer. JSON Schema can also serve this role if you prefer validator-first (Zod + `zod-to-openapi`).

---

## Integration Options Compared

| Pattern | Latency | Streaming | TS Types | Multi-host | Auth | Effort | Choose when |
|---|---|---|---|---|---|---|---|
| **Shell exec + stdout parse** | 200–1000 ms (process spawn) | No | Manual / brittle | No | None | Lowest | Prototype only; never production |
| **CLI as stable contract** (`--format json`, versioned) | 200–500 ms | No | Generated from JSON Schema | No | OS-level | Low | Infrequent calls, human-readable fallback needed, no daemon budget |
| **Long-lived daemon + UDS/named pipe** | ~130 µs | Yes (streaming JSON lines) | Generated from schema | No (single host) | Socket perms / secret handshake | Medium | High-frequency local queries, real-time context feed, single-machine deployment |
| **HTTP/JSON sidecar** (FastAPI / Flask) | 300–800 µs | SSE / chunked | Generated from OpenAPI | Yes (via URL) | Bearer token / mTLS | Medium | Multi-host, REST familiarity, existing OpenAPI tooling |
| **gRPC sidecar** | ~130 µs (UDS) / ~300 µs (TCP) | Full bidirectional | Generated from .proto | Yes | TLS / token metadata | High | Performance-critical, polyglot clients, strong contract desired |
| **FFI / native binding** | <10 µs | Yes | Manual / cffi bindings | No | N/A | Very high | Only if Python startup overhead is the true bottleneck |

**Selected recommendation:** **Long-lived local daemon + Unix domain socket with a JSON-lines protocol**, evolved toward an HTTP/JSON sidecar (FastAPI + OpenAPI) when multi-host becomes a requirement. Rationale in synthesis below.

---

## Recommended Boundary for `@miadi/tide`

### What the TS package contains

```
packages/tide/
  src/
    client.ts          # DaemonClient: connects to UDS / HTTP, sends requests, parses responses
    types.ts           # generated from tide-api.schema.json via openapi-typescript or json-schema-to-ts
    errors.ts          # TideError, TideTimeoutError, TideVersionMismatch
    transport/
      uds.ts           # Unix domain socket transport (Node net.Socket)
      http.ts          # HTTP transport fallback (multi-host)
    server-adapter.ts  # thin Next.js API Route adapter (wraps DaemonClient, adds Next.js req/res)
  schemas/
    tide-api.schema.json   # THE CONTRACT — owned here, consumed by Python & TS
  package.json           # name: "@miadi/tide", main entry, peerDeps: next (optional)
```

### How it talks to the Python runtime

1. Python daemon (`tide daemon start`) creates `~/.ironsilk/tide.sock` (UDS) on startup.
2. `DaemonClient` in TS connects once, keeps the socket open, sends newline-delimited JSON requests:
   ```json
   {"id":"req-1","method":"context.get","params":{},"version":"1"}
   ```
3. Python replies with newline-delimited JSON:
   ```json
   {"id":"req-1","result":{...},"schema_version":"1.2.0"}
   ```
4. If daemon is not running, `DaemonClient` falls back to one-shot `child_process.execFile("tide", [...])` with `--format json` — the CLI as stable plumbing fallback.
5. Multi-host future: swap transport to `HttpTransport` (pointing at FastAPI sidecar); no consumer code changes.

### How types are generated

- `schemas/tide-api.schema.json` is the source of truth.
- `pnpm run codegen` in `packages/tide` runs `openapi-typescript` or `json-schema-to-ts` to emit `src/types.ts`.
- Python reads the same schema via `jsonschema` for response validation.
- CI gate: diff on `src/types.ts` fails the build if schema changed without regeneration.

### pnpm wiring

```yaml
# pnpm-workspace.yaml
packages:
  - 'packages/*'
  - 'apps/*'
```

```json
// apps/web/package.json
"dependencies": {
  "@miadi/tide": "workspace:*"
}
```

TypeScript project references in `tsconfig.json` enable incremental builds; `composite: true` in `packages/tide/tsconfig.json`.

---

## Naming & Deprecation Migration Plan

### Phase 1 — Establish the canonical name (current sprint)

1. Decide: the public package name is `@miadi/tide`; the Python PyPI package remains `ironsilk`; the CLI entrypoint remains `tide`. Document this as the stable vocabulary in `packages/tide/AGENTS.md` and the schema file header.
2. Create `schemas/tide-api.schema.json` at `"schema_version": "1.0.0"`. All field names use `workspace` (not `scene`).

### Phase 2 — Alias, warn, bridge (MINOR releases, ~1 month)

3. In the Python daemon, emit `DeprecationWarning` (PEP 702 `@warnings.deprecated`) on any code path that receives or emits `scene`. Add `"scene"` as a documented alias field in the JSON response alongside `"workspace"` for one release cycle.
4. In the Next.js API route (`app/api/context/route.ts`), replace the raw `exec` call with `DaemonClient` from `@miadi/tide`. The old route stays as a deprecated alias (HTTP 301 or `X-Deprecated: true` header).
5. Update `~/.hermes` state root: daemon reads from both `~/.hermes` and `~/.ironsilk`, writes only to `~/.ironsilk`. Log a one-time migration notice on first run.

### Phase 3 — Remove (MAJOR bump, ≥ 2 release cycles later)

6. Drop `scene` alias from schema → bump `schema_version` to `2.0.0`, bump `@miadi/tide` to `2.0.0`.
7. Stop reading `~/.hermes`. Add `reserved` annotation in JSON Schema `$comment` for the field name `scene` to prevent reuse.
8. Update CHANGELOG and migration guide (one section per removed alias).

### Codename retirement

| Old name | New canonical | Retirement action |
|---|---|---|
| `hermes-navigator` | `ironsilk` (PyPI) | README redirect; PyPI package marked deprecated (`pip install ironsilk`) |
| `~/.hermes` | `~/.ironsilk` | Phase 3 above |
| `scene` | `workspace` | Phase 2–3 above |
| `packages/tide` stub | `@miadi/tide` real package | This sprint |

---

## Cautions

- **Hardcoded path anti-pattern:** `/home/jgi/anaconda3/bin/tide` must be replaced with PATH resolution (`which tide` or `env.TIDE_BIN`). The `DaemonClient` should accept a configurable socket path via env (`TIDE_SOCKET`, default `~/.ironsilk/tide.sock`).
- **10-second timeout:** appropriate for cold CLI spawn; inadequate if daemon is running (UDS round-trip should be < 5 ms). Separate timeout values per transport.
- **No auth on UDS:** Unix socket file permissions (`chmod 0600`, owned by the running user) are sufficient for single-user local use. Add a shared-secret handshake (`{"auth":"<token>"}` on first connect) before exposing over TCP.
- **CLI fallback creates spawn cost:** `child_process.execFile` spawns a Python interpreter each call (~200–500 ms). Acceptable for rare fallback; unacceptable as primary path.
- **Schema drift:** without CI enforcement, the JSON Schema in `packages/tide/schemas/` will diverge from the Python daemon's actual output. Add a pact/contract test (Pact or a simple golden-file test) to the Python test suite.

---

## Engineering Implications

- The `@miadi/tide` package makes the Next.js app deployable without hardcoded host paths; the transport layer is the only host-specific configuration.
- The schema-first approach means a new agent consumer (e.g., a CLI tool, another Next.js instance) gets types for free by installing `@miadi/tide`.
- The daemon model reduces Python startup overhead from every request to once per session — critical for interactive UX.
- The migration plan follows SemVer strictly: aliases live in MINOR, removals only in MAJOR, with documented warning periods matching Python's ≥2-release minimum and Node.js's deprecation list pattern.

---

## Sources

| Title | Author/Venue | Year | URL | Verified | Claim supported |
|---|---|---|---|---|---|
| Semantic Versioning 2.0.0 | Tom Preston-Werner / semver.org | 2013 (living) | https://semver.org | true | MAJOR/MINOR/PATCH rules; deprecation sequence |
| Git Internals – Plumbing and Porcelain | Pro Git Book / git-scm.com | 2014 (living) | https://git-scm.com/book/en/v2/Git-Internals-Plumbing-and-Porcelain | true | plumbing/porcelain stable-contract philosophy |
| Stripe API Versioning | Stripe Documentation | 2026 | https://docs.stripe.com/api/versioning | true | Date-based pinning; SDK SemVer + API epoch split |
| PEP 387 – Backwards Compatibility Policy | Python Core / peps.python.org | 2009 (living) | https://peps.python.org/pep-0387/ | true | 2-release minimum deprecation window |
| PEP 702 – Marking deprecations using the type system | Python Core / peps.python.org | 2023 | https://peps.python.org/pep-0702/ | true | `@warnings.deprecated()` typed deprecation |
| Node.js Releases | nodejs.org | 2026 | https://nodejs.org/en/about/previous-releases | true | Current → LTS → Maintenance → EOL lifecycle |
| pnpm Workspaces | pnpm.io | 2026 | https://pnpm.io/workspaces | true | `workspace:*` protocol; single lockfile; publish conversion |
| The Node.js Developer's Guide to Unix Domain Sockets: 50% Lower Latency | NodeVibe / Substack | 2024 | https://nodevibe.substack.com/p/the-nodejs-developers-guide-to-unix | true | UDS 130 µs vs TCP loopback 334 µs |
| gRPC Introduction | grpc.io | 2026 | https://grpc.io/docs/what-is-grpc/introduction/ | true | protobuf IDL, polyglot codegen |
| Protocol Buffers: Reserved and Deprecated Fields | Sanh Doan / Medium | 2024 | https://medium.com/@sanhdoan/protocol-buffers-the-importance-of-reserved-and-deprecated-fields-bbb8d7d3211d | true | protobuf field deprecation and `reserved` discipline |
| openapi-typescript | openapi-ts.dev | 2026 | https://openapi-ts.dev/ | true | Runtime-free TS type generation from OpenAPI |
| IPC Performance Comparison | Baeldung on Linux | 2024 | https://www.baeldung.com/linux/ipc-performance-comparison | true | Relative IPC mechanism latency rankings |
