@amalgm/apps 0.1.3-main.34175702358 → 0.1.3-main.34319249002

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/PURPOSE.md CHANGED
@@ -10,11 +10,11 @@ app keeps one stable identity while every deployment names an immutable
10
10
  release, failed deployments leave the last working release recoverable, and
11
11
  rollback means activating known bytes rather than rebuilding history.
12
12
 
13
- Amalgm Shell is the composition root for the complete Amalgm runtime. This
14
- repository owns the Apps product and its supervisor. Shell composes that
15
- product beside Files, Chat and other products through their public contracts;
16
- it supplies identity, transport and machine adapters without absorbing their
17
- domain supervisors or maintaining a second app lifecycle implementation.
13
+ Amalgm Shell is the active machine composition root. This repository owns the
14
+ Apps product and its stateful supervisor. Shell may instantiate Apps, supply
15
+ identity and routing effects, and expose its public adapters, but it does not
16
+ absorb app lifecycle decisions or maintain a second Apps registry. Amalgm
17
+ Engine is deprecated historical and parity evidence only.
18
18
 
19
19
  Runtime hosts may mount the Apps HTTP catalog, including its legacy Artifacts
20
20
  projection, without becoming lifecycle authorities. Catalog reads come from
@@ -32,9 +32,8 @@ the same Apps store as the SDK, CLI, and MCP surfaces.
32
32
  deployment.
33
33
  - The **Apps supervisor** is the sole lifecycle authority for apps in one
34
34
  Apps state directory.
35
- - A **product-service supervisor** is an optional outer Shell concern that
36
- observes whether the Apps product is available; it never supervises
37
- individual apps.
35
+ - A **product-service supervisor** is an optional host concern that observes
36
+ whether the Apps product is available; it never supervises individual apps.
38
37
  - The **data directory** is stable writable storage for an app across
39
38
  deployments; release and deployment files are not persistent data.
40
39
 
@@ -82,8 +81,8 @@ locked dependency graph on the supported Node toolchain.
82
81
  is derived from desired state, process state, health, and DNS connection.
83
82
  9. App code receives a stable data directory explicitly; writes made inside a
84
83
  deployment directory never become part of a release or a later deploy.
85
- 10. The SDK owns behavior. CLI, MCP, HTTP, and Shell integrations only adapt
86
- that public service.
84
+ 10. The SDK owns behavior. CLI, MCP, HTTP, Shell, and other host integrations
85
+ only adapt that public service.
87
86
  11. Apps stores tool identifiers as opaque references and never edits Toolbox,
88
87
  Agents, or another product. Any workflow spanning products has an explicit
89
88
  product owner and never lives in a Core adapter.
@@ -91,9 +90,10 @@ locked dependency graph on the supported Node toolchain.
91
90
  crash or keep the hosted app alive by itself.
92
91
  13. The Apps supervisor belongs to this product in standalone and composed
93
92
  deployments; exactly one active Apps supervisor owns a state directory.
94
- 14. Shell composes product supervisors side by side. It may supervise the
93
+ 14. Shell composes product capabilities and host effects. It may supervise the
95
94
  Apps product as one service, but it never reaches through that boundary to
96
- start, stop, adopt, or restart an individual app process.
95
+ start, stop, adopt, or restart an individual app process outside the Apps
96
+ public service.
97
97
  15. Supervisor state is scoped to its fault domain: an app failure changes
98
98
  Apps state, an Apps-service failure changes Apps availability, and neither
99
99
  is represented as failure of an unrelated product.
@@ -112,6 +112,9 @@ locked dependency graph on the supported Node toolchain.
112
112
  21. An awaited lifecycle mutation resolves only after its ordered embedder
113
113
  change notifications settle; observer failures are reported and contained.
114
114
 
115
+ The packaged Apps skill describes these public adapters and is distributed with
116
+ the same SDK source; it owns no installation or lifecycle implementation.
117
+
115
118
  ## Predictable behavior
116
119
 
117
120
  Equal source and manifest content produces the same release id, even when
@@ -121,5 +124,5 @@ new deployment. Renaming changes only the app record. If validation or build
121
124
  fails, the running deployment is untouched. If the new process cannot start,
122
125
  the deployment is marked failed and the previous deployment is reactivated.
123
126
  When composed into Shell, the same Apps supervisor makes those decisions.
124
- Shell sees the Apps product as available, degraded, or unavailable and can
127
+ Shell may observe the Apps product as available, degraded, or unavailable and
125
128
  restart that product independently without becoming a second app supervisor.
package/README.md CHANGED
@@ -53,20 +53,21 @@ const http = createAppsHttpServer(apps);
53
53
  await http.listen();
54
54
  ```
55
55
 
56
- It serves modern `/apps` and engine-compatible `/apps/list` catalogs plus
56
+ It serves modern `/apps` and legacy-compatible `/apps/list` catalogs plus
57
57
  their `/artifacts` legacy projection. Lifecycle choices remain on the SDK,
58
58
  CLI, and MCP surfaces; this HTTP increment is read-only.
59
59
 
60
60
  The SDK, supervisor, CLI, MCP server, lease, and tests are authored in
61
- TypeScript. `npm run build` emits the CommonJS runtime and declarations into
61
+ TypeScript. `npm run build` emits the ESM runtime and declarations into
62
62
  `dist/`; generated output is not a second source tree.
63
63
 
64
- Engine supplies runtime identity, route publication, and state notifications
65
- through constructor callbacks; it does not replace product behavior. The
66
- ownership and generated-source boundary are described in
67
- [docs/ENGINE_INTEGRATION.md](./docs/ENGINE_INTEGRATION.md). Supervisor
68
- ownership and the shared composition pattern for Apps, Events, and Realtime
69
- are defined in [docs/SUPERVISION.md](./docs/SUPERVISION.md).
64
+ Shell supplies machine identity, route publication, host effects, and state
65
+ projection through public adapters; it does not replace product behavior. The
66
+ active boundary is described in
67
+ [docs/SHELL_INTEGRATION.md](./docs/SHELL_INTEGRATION.md). Supervisor ownership
68
+ is defined in [docs/SUPERVISION.md](./docs/SUPERVISION.md). The old
69
+ [Engine integration](./docs/ENGINE_INTEGRATION.md) page is retained only as a
70
+ historical cutover note.
70
71
 
71
72
  ## Verify
72
73
 
@@ -1,68 +1,12 @@
1
- # Engine integration
1
+ # Historical Engine integration
2
2
 
3
- `@amalgm/apps` is the canonical Apps product. Amalgm Engine embeds a generated
4
- copy so the Engine runtime and the standalone package execute the same service
5
- implementation.
3
+ Amalgm Engine is deprecated. It is useful only as read-only evidence for
4
+ legacy request shapes, migrations, and parity vectors. It is not a runtime
5
+ composer, source-flow destination, generated-product host, or fallback for
6
+ `@amalgm/apps`.
6
7
 
7
- ## Ownership boundary
8
+ The former workflow copied generated Apps output into Engine. That workflow is
9
+ retired: product changes begin and remain in this repository, and active
10
+ machine composition uses the published package through `@amalgm/shell`.
8
11
 
9
- Apps owns:
10
-
11
- - app, release, deployment, process, and health state;
12
- - validation, packaging, builds, activation, rollback, and supervision;
13
- - the SDK, CLI commands, MCP tool definitions, and the app-side lease.
14
-
15
- In the target independently supervised composition, Engine owns:
16
-
17
- - runtime URLs, authentication, ports, and public route publication;
18
- - outer service-level availability and restart policy for the Apps product;
19
- - state-event and UI composition;
20
- - mechanical projection of Apps records into shared client surfaces;
21
- - one-time import from Engine's superseded `apps.json` registry.
22
-
23
- Engine adapters must call the public `Apps` service. They must not write the
24
- Apps database, deployment directories, or release directories directly.
25
- Engine's outer supervisor treats Apps as one product service and never starts,
26
- stops, adopts, or restarts an individual app. The complete hierarchy is in
27
- [SUPERVISION.md](./SUPERVISION.md).
28
-
29
- ## Source flow
30
-
31
- From an Engine checkout next to this repository:
32
-
33
- ```sh
34
- npm run apps:sync
35
- ```
36
-
37
- Engine's `scripts/sync-products.mjs apps` builds the canonical TypeScript source,
38
- then copies `PURPOSE.md`, `package.json`, and generated `dist/` into
39
- `runtime/products/apps/`. It also writes `SOURCE.json` with the product
40
- version, source commit, and a deterministic content digest.
41
- `npm run apps:check` rejects generated drift without rewriting files. The
42
- Engine npm package copies that generated runtime during its existing runtime
43
- sync.
44
-
45
- Make product changes here first, verify them here, then sync Engine. Files
46
- under Engine's `runtime/products/apps/` are generated artifacts and are not
47
- edited by hand.
48
-
49
- ## Composition
50
-
51
- The `amalgm apps ...` command uses the generated product CLI with an HTTP
52
- client for Engine's long-lived service. This keeps command parsing canonical
53
- without creating a competing process supervisor. Engine's MCP server mounts
54
- the product's MCP tool definitions over the same lazily resolved service.
55
- Engine REST routes adapt their request and response shapes to it.
56
-
57
- The event tunnel and local gateway use one shared Engine adapter that reads
58
- routable ports from the product database. Runtime route readers never consult
59
- the superseded registry.
60
-
61
- On boot, Engine imports each existing app once while preserving its stable id,
62
- app ref, public URL, port, desired state, and live process when possible.
63
- Import progress is recorded independently. Invalid source data blocks cleanup
64
- and remains recoverable; it never becomes a fallback runtime registry.
65
-
66
- Apps and Tools may contain references to one another, but neither adapter
67
- silently rewrites the other product. A workflow that intentionally changes
68
- both must have an explicit owner outside Core's transport adapters.
12
+ See [SHELL_INTEGRATION.md](./SHELL_INTEGRATION.md) for the current boundary.
@@ -0,0 +1,39 @@
1
+ # Shell integration
2
+
3
+ `@amalgm/apps` is the canonical Apps product. `@amalgm/shell` is the active
4
+ machine composer and imports the published package; it does not copy Apps
5
+ source or keep a second registry.
6
+
7
+ ## Ownership boundary
8
+
9
+ Apps owns:
10
+
11
+ - app, release, deployment, process-generation, and health state;
12
+ - validation, packaging, builds, activation, rollback, and supervision;
13
+ - its SQLite store and release/deployment directories;
14
+ - SDK, CLI, MCP, HTTP, and app-side lease behavior.
15
+
16
+ Shell owns:
17
+
18
+ - the exact package version used by a Shell release;
19
+ - machine identity, authenticated route mounting, and host effects;
20
+ - selection of the machine-local Apps state directory;
21
+ - projection of the Apps catalog into runtime and UI surfaces; and
22
+ - orderly construction and shutdown of the one Apps service instance it owns.
23
+
24
+ Core supplies portable admission and supervision decision contracts. Neither
25
+ Core nor Shell writes the Apps database, starts an app process outside the
26
+ Apps public service, or reimplements release and deployment behavior.
27
+
28
+ ## Current release boundary
29
+
30
+ Shell imports Apps and mounts its HTTP/MCP adapters in composed and development
31
+ hosts. In the signed machine host, Apps is initialized lazily when its selected
32
+ Toolbox route is invoked. The current signed service catalog still names Core,
33
+ Files, Agents, Tools, and Chat; a package dependency or mounted route is not by
34
+ itself admission as an independently booted signed service.
35
+
36
+ ## Engine evidence
37
+
38
+ Legacy `/apps`, `/artifacts`, app-ref, and migration shapes may be compared with
39
+ Engine read-only. Engine never runs beside Shell and is never a fallback.
@@ -1,36 +1,36 @@
1
1
  # Supervision ownership
2
2
 
3
- The Apps supervisor stays in `@amalgm/apps`. Standalone use and Amalgm Engine
3
+ The Apps supervisor stays in `@amalgm/apps`. Standalone use and Amalgm Shell
4
4
  composition execute the same supervisor; combining products does not move app
5
- lifecycle logic into Engine.
5
+ lifecycle logic into Shell or Core.
6
6
 
7
- ## Target Engine composition
7
+ ## Active composition
8
8
 
9
9
  ```text
10
- Amalgm Engine
11
- ├── Apps product-service supervisor
12
- │ └── @amalgm/apps supervisor
13
- │ ├── App A process generations
14
- │ └── App B process generations
15
- ├── Events product-service supervisor
16
- │ └── @amalgm/events supervisor
17
- └── Realtime product-service supervisor
18
- └── @amalgm/realtime supervisor
10
+ @amalgm/shell
11
+ ├── Core identity, transport, and portable supervision policy
12
+ └── @amalgm/apps public service
13
+ └── @amalgm/apps supervisor
14
+ ├── App A process generations
15
+ └── App B process generations
19
16
  ```
20
17
 
21
- Each product owns its domain supervisor. Engine composes those supervisors
22
- side by side and may provide an outer service supervisor for each product.
23
- The two levels have different authority:
18
+ Apps owns its domain supervisor. Shell constructs the product once for the
19
+ selected state directory and supplies host effects. Core owns portable route
20
+ admission, health vocabulary, and restart decision contracts; it does not own
21
+ the Apps store or a stateful app-process supervisor. The levels have different
22
+ authority:
24
23
 
25
24
  | Supervisor | Owns | Does not own |
26
25
  | --- | --- | --- |
27
- | Apps supervisor | app desired state, deployments, process generations, health, restart budgets | Engine lifecycle or other products |
26
+ | Apps supervisor | app desired state, deployments, process generations, health, restart budgets | Shell lifecycle or other products |
28
27
  | Apps product-service supervisor | Apps-service availability, service restart budget, shutdown and readiness | individual app processes or the Apps database |
29
- | Engine composition | identity, transport, UI projection, cross-product relationships | product lifecycle state |
28
+ | Core contracts | app-route admission, health vocabulary, portable restart decisions | Apps persistence or process ownership |
29
+ | Shell composition | machine effects, identity, route mounting, product availability | app lifecycle decisions or Apps persistence |
30
30
 
31
- There is never a second Apps supervisor in Engine. Engine either instantiates
32
- the supervisor exported by this product or communicates with a service that
33
- does. CLI, MCP, HTTP, gateways, and UI code are clients or adapters.
31
+ There is never a second Apps supervisor in Shell or Core. Shell instantiates
32
+ the public Apps service or communicates with a process that does. CLI, MCP,
33
+ HTTP, gateways, and UI code are clients or adapters.
34
34
 
35
35
  ## One owner per state directory
36
36
 
@@ -49,13 +49,14 @@ Failures remain inside the smallest responsible supervisor:
49
49
 
50
50
  - an app crash is handled by the Apps supervisor and changes only that app;
51
51
  - an exhausted app restart budget degrades that app, not the Apps service;
52
- - an Apps-service failure makes Apps unavailable to Engine;
53
- - Engine may restart or disable the Apps service without restarting Events,
54
- Realtime, or the rest of the runtime;
55
- - Engine never repairs an Apps-service failure by editing app process state.
52
+ - an Apps-service failure makes Apps unavailable to Shell;
53
+ - Shell may restart or disable the Apps service without restarting unrelated
54
+ products or the rest of the runtime;
55
+ - Shell and Core never repair an Apps-service failure by editing app process
56
+ state.
56
57
 
57
- This distinction is what allows Amalgm Engine to contain many products without
58
- recreating a monolithic supervisor.
58
+ This distinction is what lets Shell compose many products without recreating a
59
+ monolithic supervisor.
59
60
 
60
61
  ## Lifecycle modes
61
62
 
@@ -67,7 +68,7 @@ The Apps supervisor owns both product behaviors:
67
68
  - **always on** — the supervisor starts the app with the service and applies
68
69
  its durable restart budget while the desired state remains running.
69
70
 
70
- These are policies of the Apps supervisor. Engine may request a policy change,
71
+ These are policies of the Apps supervisor. A host may request a policy change,
71
72
  but it does not implement the policy itself. Explicit `start` and `stop`
72
73
  already provide the no-rebuild process mechanics; the first-class
73
74
  `runtimeMode` and idle policy remain to be implemented.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@amalgm/apps",
3
- "version": "0.1.3-main.34175702358",
3
+ "version": "0.1.3-main.34319249002",
4
4
  "description": "Local-first, versioned application deployment for Amalgm.",
5
5
  "license": "UNLICENSED",
6
6
  "private": false,
@@ -36,6 +36,7 @@
36
36
  "files": [
37
37
  "docs",
38
38
  "dist",
39
+ "skills",
39
40
  "PURPOSE.md",
40
41
  "README.md"
41
42
  ],
@@ -56,7 +57,7 @@
56
57
  "node": ">=24"
57
58
  },
58
59
  "dependencies": {
59
- "@amalgm/core": "0.4.8-main.34168902443",
60
+ "@amalgm/core": "0.5.1-main.34318359436",
60
61
  "@types/better-sqlite3": "^7.6.13",
61
62
  "@types/node": "^20.19.43",
62
63
  "better-sqlite3": "^12.6.2",
@@ -88,11 +89,11 @@
88
89
  "package.json"
89
90
  ]
90
91
  },
91
- "gitHead": "9cf35173f380adb6ba4998c13aa854a2967fa11c",
92
+ "gitHead": "c3c8ce3fed19380be92fb5977eef54623fbafae6",
92
93
  "amalgmSource": {
93
94
  "repository": "amalgm-inc/amalgm-apps",
94
95
  "branch": "main",
95
- "commit": "9cf35173f380adb6ba4998c13aa854a2967fa11c",
96
- "occurrence": "34175702358"
96
+ "commit": "c3c8ce3fed19380be92fb5977eef54623fbafae6",
97
+ "occurrence": "34319249002"
97
98
  }
98
99
  }
@@ -0,0 +1,280 @@
1
+ ---
2
+ name: apps
3
+ description: Turn any runnable project into a locally owned, versioned application that Amalgm keeps alive — declare an amalgm.app.json, register it, and get immutable releases, one-command deploys and rollbacks, crash restarts, health monitoring, and a stable public URL without a remote hosting platform. Use when building, deploying, or operating an Amalgm app, writing an app manifest, wiring the ready/heartbeat health lease, driving the apps CLI or MCP tools, or embedding the Apps SDK in your own service.
4
+ ---
5
+
6
+ # Amalgm Apps
7
+
8
+ Apps turns any runnable project — any language, any framework — into a versioned application that Amalgm keeps alive on your machine. You describe the app once in an `amalgm.app.json` manifest and register it; from then on every deploy produces an immutable, content-addressed release, rollback is a one-command return to bytes that already exist, crashes are restarted automatically with backoff, and your app gets a stable identity: an id, an app ref, a port, and a public URL that all survive deploys, rollbacks, and renames. There is no remote build farm and no hosting account — state lives on disk under your Amalgm home directory, and the same SDK powers the CLI, the MCP tools, and the HTTP catalog.
9
+
10
+ ## Installation
11
+
12
+ Everything ships in one npm package:
13
+
14
+ ```bash
15
+ npm install @amalgm/apps
16
+ ```
17
+
18
+ The package exposes four entry points, so you only import what your integration needs:
19
+
20
+ - `@amalgm/apps` — the full SDK: the `Apps` service class, `defaultStateDir`, `runCli`, manifest helpers (`readManifest`, `normalizeManifest`), package helpers (`inspectPackage`, `packPackage`, `unpackPackage`, `validatePackageFiles`, `materialize`), and MCP factories (`createMcpTools`, `createMcpServer`).
21
+ - `@amalgm/apps/lease` — the tiny client your *hosted app* imports to announce health: `connect`, `ready`, `heartbeat`, `grants`, `isManaged`. Zero configuration; inert outside Amalgm.
22
+ - `@amalgm/apps/http` — `createAppsHttpServer`, a read-only HTTP catalog of your apps for dashboards and embedders.
23
+ - `@amalgm/apps/mcp` — the MCP tool definitions alone, for hosts that assemble their own MCP server.
24
+
25
+ Installing the package also gives you two binaries: `amalgm-apps` (the CLI) and `amalgm-apps-mcp` (a stdio MCP server), both runnable with `npx`.
26
+
27
+ Node.js 24 or newer is required.
28
+
29
+ ## Quickstart
30
+
31
+ Say you have a small Node server in `./hello`:
32
+
33
+ ```ts
34
+ // hello/server.js
35
+ import http from 'node:http';
36
+ http
37
+ .createServer((_req, res) => res.end('hello from an Amalgm app'))
38
+ .listen(process.env.PORT);
39
+ ```
40
+
41
+ Add an `amalgm.app.json` next to it:
42
+
43
+ ```json
44
+ {
45
+ "schemaVersion": 1,
46
+ "name": "Hello",
47
+ "description": "A minimal Amalgm app",
48
+ "buildCommand": null,
49
+ "startCommand": "node server.js",
50
+ "package": { "include": ["server.js"], "exclude": [] }
51
+ }
52
+ ```
53
+
54
+ Register it:
55
+
56
+ ```bash
57
+ npx --yes --package @amalgm/apps amalgm-apps register ./hello
58
+ ```
59
+
60
+ That single command validates the manifest, packages the included files into a release, deploys it, starts the process on an assigned port, and prints the app as JSON — including its `id`, `appRef`, `port`, and `publicUrl`. Ship a new version any time with `npx --yes --package @amalgm/apps amalgm-apps deploy <app-id>`, and step back with `npx --yes --package @amalgm/apps amalgm-apps rollback <app-id>`.
61
+
62
+ The same flow from TypeScript:
63
+
64
+ ```ts
65
+ import { Apps } from '@amalgm/apps';
66
+
67
+ const apps = new Apps();
68
+ const app = await apps.register({ cwd: './hello' });
69
+ console.log(app.publicUrl, app.port);
70
+ await apps.close();
71
+ ```
72
+
73
+ Continuous crash recovery and health monitoring require a long-lived Apps owner: Shell, the Apps MCP server, or an embedding service that calls `apps.boot()`. The CLI performs one operation and then releases its Apps owner. Use one owner for each state directory.
74
+
75
+ ## The app manifest
76
+
77
+ `amalgm.app.json` at the project root is the only integration contract. Its full shape:
78
+
79
+ ```ts
80
+ interface AppManifest {
81
+ schemaVersion: 1; // must be exactly 1
82
+ name: string; // required, non-empty
83
+ description: string; // optional in the file; '' when absent
84
+ buildCommand: string | null; // null skips the build step
85
+ startCommand: string; // required; '{port}' expands to the app's port
86
+ toolIds: string[]; // optional; opaque references to Amalgm tools
87
+ package: {
88
+ include: string[]; // required; must select at least one file
89
+ exclude: string[]; // optional
90
+ };
91
+ }
92
+ ```
93
+
94
+ Rules worth knowing before your first deploy:
95
+
96
+ - Unknown fields are rejected, not ignored — a typo like `"startCmd"` fails validation with a message naming the field.
97
+ - `package.include` and `package.exclude` are glob patterns; `include` must match at least one file. Only included files become part of a release, so build outputs your `startCommand` needs must be covered.
98
+ - `buildCommand: null` means "no build step". When set, it runs once per new release, before the release is activated.
99
+ - `startCommand` runs with the deployment directory as its working directory. Write `{port}` anywhere in it to interpolate the assigned port, or just read the `PORT` environment variable.
100
+
101
+ Check a project without deploying it:
102
+
103
+ ```bash
104
+ npx --yes --package @amalgm/apps amalgm-apps validate ./hello
105
+ ```
106
+
107
+ This prints the parsed manifest, the release digest, the exact files that would be packaged, and anything excluded — the fastest way to debug an `include` pattern.
108
+
109
+ ## Lifecycle
110
+
111
+ Three nouns cover everything you will observe:
112
+
113
+ - An **app** is a stable identity. Its `id`, `appRef`, `port`, and `publicUrl` are assigned at registration and never change; the manifest seeds the display name, and only `rename` changes it afterward.
114
+ - A **release** is an immutable, content-addressed snapshot of your manifest plus packaged files. Deploying the same bytes twice yields the same release id — an existing release is never rebuilt.
115
+ - A **deployment** activates exactly one release. Deployment history is append-only, and a rollback appends a new deployment of an *existing* release — old bytes, never a rebuild.
116
+
117
+ ```ts
118
+ const app = await apps.register({ cwd: './hello' }); // returns an AppView
119
+ await apps.deploy(app.id); // package sourceDir again -> new release if bytes changed
120
+ await apps.rollback(app.id); // previous release; or apps.rollback(id, { releaseId })
121
+ await apps.rename(app.id, 'Hello v2');
122
+ apps.versions(app.id); // Release[]
123
+ apps.deployments(app.id); // Deployment[]
124
+ await apps.start(app.id); // start the current deployment, no rebuild
125
+ await apps.stop(app.id);
126
+ await apps.delete(app.id); // stops the process, removes all state and files
127
+ ```
128
+
129
+ ### Safe deploys
130
+
131
+ Validation, packaging, and the build all finish **before** the currently running process is stopped, so a broken build never takes down the running version. If the newly started process dies inside its startup grace period (about one second), the deployment is marked `failed` and the previous runnable deployment is reactivated automatically.
132
+
133
+ The statuses you will see in `deployments` and process history:
134
+
135
+ ```ts
136
+ type DeploymentStatus = 'prepared' | 'active' | 'superseded' | 'failed';
137
+ type GenerationStatus = 'starting' | 'running' | 'failed' | 'crashed' | 'exited';
138
+ ```
139
+
140
+ ### Keep-alive and health states
141
+
142
+ Amalgm supervises every registered app. When your process crashes, it is restarted in place — same deployment directory, no copying, no rebuild — with exponential backoff (starting around 2 seconds, capped at 60). An app that crashes 5 times inside a 5-minute window has exhausted its restart budget and is marked `degraded` instead of being restarted forever; that budget survives restarts of Amalgm itself, and an exhausted budget affects only that one app. An explicit `start` resets the budget.
143
+
144
+ An app's `status` field moves through:
145
+
146
+ ```ts
147
+ type AppStatus =
148
+ | 'registered' | 'building' | 'running' | 'restarting'
149
+ | 'degraded' | 'error' | 'stopped' | 'unresponsive';
150
+ ```
151
+
152
+ `unresponsive` appears only for apps that opted into heartbeats (next section) and then went silent; the process is still alive — the status is honest reporting, not a kill. A resumed heartbeat flips it back to `running`.
153
+
154
+ ### Your app's environment
155
+
156
+ Every hosted process receives:
157
+
158
+ | Variable | Meaning |
159
+ | --- | --- |
160
+ | `PORT` | The port your server must listen on |
161
+ | `AMALGM_APP_ID` | The app's stable id |
162
+ | `AMALGM_APP_REF` | The app's stable ref (the subdomain) |
163
+ | `AMALGM_APP_URL` | The app's public URL |
164
+ | `AMALGM_APP_DATA_DIR` | The only directory where persistent data belongs |
165
+
166
+ Write durable data **only** to `AMALGM_APP_DATA_DIR`. It survives deploys and rollbacks; anything written inside a deployment directory does not, and never becomes part of a later release.
167
+
168
+ Each app records `https://<appRef>.<domain>/` (default domain `apps.amalgm.ai`) and a port allocated from 9100–9199 by default. Public reachability requires the composing host to publish that route and provide DNS and transport.
169
+
170
+ ## The health lease
171
+
172
+ By default Amalgm only knows whether your process is alive. Opt into real health reporting from inside your app with the lease client — one import, one call:
173
+
174
+ ```ts
175
+ import { connect } from '@amalgm/apps/lease';
176
+
177
+ const lease = connect({ heartbeatIntervalMs: 30_000 }); // 30s is the default
178
+ // on shutdown: lease.stop()
179
+ ```
180
+
181
+ `connect` announces readiness once, then heartbeats on the interval you chose. Choose 5 seconds to 5 minutes; the host clamps its expected interval to that range. Miss 3 consecutive expected beats and your app shows as `unresponsive` until beats resume.
182
+
183
+ The lease is deliberately boring and safe:
184
+
185
+ - Outside Amalgm — running `node server.js` on your laptop, in CI, in a container — it is inert: `isManaged()` returns `false` and `connect` returns `{ active: false, stop() {} }`. You never need an environment check around it.
186
+ - Transport failures surface through an optional `onError` callback (or a console warning once per failure period). Keep the callback nonthrowing. The heartbeat timer never keeps your process alive on its own.
187
+
188
+ Lower-level pieces when you want manual control:
189
+
190
+ ```ts
191
+ import { grants, isManaged, ready, heartbeat } from '@amalgm/apps/lease';
192
+
193
+ if (isManaged()) {
194
+ const { appId, appRef, publicUrl, dataDir, port } = grants();
195
+ await ready({ heartbeatIntervalMs: 10_000 });
196
+ setInterval(() => heartbeat(), 10_000);
197
+ }
198
+ ```
199
+
200
+ ## CLI
201
+
202
+ `amalgm-apps` takes a command plus arguments, prints results as JSON, and exits non-zero on failure. The commands you will actually use day to day:
203
+
204
+ ```bash
205
+ amalgm-apps register <dir> # validate, release, deploy, and start in one step
206
+ amalgm-apps validate <dir> # dry-run: manifest, digest, packaged files
207
+ amalgm-apps list # all apps with status and health
208
+ amalgm-apps show <app-id> # one app in full detail
209
+ amalgm-apps deploy <app-id> [dir] # new release from the source dir (or a new dir)
210
+ amalgm-apps rollback <app-id> [release-id]
211
+ amalgm-apps versions <app-id> # release history
212
+ amalgm-apps deployments <app-id> # deployment history with statuses
213
+ amalgm-apps start <app-id>
214
+ amalgm-apps stop <app-id>
215
+ amalgm-apps delete <app-id> # stop and remove everything
216
+ ```
217
+
218
+ `register` accepts a few flags: `--port <n>` to pin a specific port, `--no-autostart` to register without launching, `--no-keep-alive` to disable crash restarts, and `--no-dns` to keep the app off the public route table. Every command also accepts a global `--state-dir <dir>` to operate on a non-default state directory.
219
+
220
+ ## MCP tools
221
+
222
+ Run `npx --yes --package @amalgm/apps amalgm-apps-mcp` for a stdio MCP server, or embed the tools in your own host:
223
+
224
+ ```ts
225
+ import { Apps, createMcpTools, createMcpServer } from '@amalgm/apps';
226
+
227
+ const tools = createMcpTools(new Apps()); // name, description, inputSchema, handler
228
+ const server = createMcpServer(); // or a full JSON-RPC server: server.start()
229
+ ```
230
+
231
+ The tools mirror the CLI one-for-one: `apps_register`, `apps_validate`, `apps_list`, `apps_show`, `apps_deploy`, `apps_versions`, `apps_deployments`, `apps_rollback`, `apps_rename`, `apps_start`, `apps_stop`, `apps_connect_dns`, `apps_disconnect_dns`, and `apps_delete`. This is how an agent connected to Amalgm ships and operates apps on your behalf.
232
+
233
+ For read-only visibility — a dashboard, a status page — mount the HTTP catalog:
234
+
235
+ ```ts
236
+ import { Apps, createAppsHttpServer } from '@amalgm/apps';
237
+
238
+ const server = createAppsHttpServer(new Apps());
239
+ ```
240
+
241
+ It serves `GET /apps` (and `/apps/list`) plus `/apps/routes`. It is strictly a catalog: all lifecycle changes go through the SDK, CLI, or MCP tools.
242
+
243
+ ## Where state lives
244
+
245
+ Apps keeps everything under one state directory. The standalone main binding defaults to `~/.amalgm/users/<scope>/apps`; preview and local bindings use separate namespaces under `~/.amalgm/environments/`. A composed host supplies its installation root through `AMALGM_ROOT`. Point it elsewhere with the `AMALGM_APPS_DIR` environment variable (used verbatim), `AMALGM_DIR` (state goes in an `apps/` folder under it), or the `stateDir` option / `--state-dir` flag.
246
+
247
+ Inside you will find, per app:
248
+
249
+ ```
250
+ apps.db # the SQLite catalog: apps, releases, deployments, history
251
+ releases/<app-id>/ # immutable release contents, one directory per release
252
+ deployments/<app-id>/# the working copies your process actually runs from
253
+ data/<app-id>/ # your app's AMALGM_APP_DATA_DIR — survives every deploy
254
+ logs/<app-id>.log # captured stdout/stderr, rotated once at <app-id>.log.1
255
+ ```
256
+
257
+ Treat these directories as read-only observability: inspect the logs, browse a release, back up `data/` — but let the CLI, SDK, and MCP tools make the changes. `delete` removes an app's releases, deployments, data, and logs in one step.
258
+
259
+ ## Embedding the SDK
260
+
261
+ If you are building a long-lived service that hosts apps itself, construct one `Apps` instance and run its daemon lifecycle:
262
+
263
+ ```ts
264
+ import { Apps } from '@amalgm/apps';
265
+
266
+ const apps = new Apps({
267
+ stateDir: '/var/lib/amalgm/apps',
268
+ publishRoutes: (routes, reason) => gateway.update(routes), // eligible routes changed
269
+ onChange: (app) => events.emit('app', app), // app updated, or { id, deleted: true }
270
+ onError: (error) => log.warn(error),
271
+ });
272
+
273
+ await apps.boot(); // take ownership, start health sweeps, resume apps
274
+ // ... serve ...
275
+ await apps.close({ stopProcesses: true }); // stop hosted apps on the way down
276
+ ```
277
+
278
+ `boot()` adopts apps that should be running and resumes health monitoring; `close()` without `stopProcesses: true` detaches and leaves processes running for the next owner. Your callbacks are fault boundaries — an exception inside them is reported through `onError` and contained, never allowed to take the daemon down. `apps.routes()` returns the currently eligible `{ app_ref, port, name }` routes; routes fail closed, so an app that is stopped, degraded, or disconnected from DNS simply disappears from the table.
279
+
280
+ Only one live Apps service may manage a given state directory at a time; a second instance pointed at the same directory will refuse to take ownership rather than corrupt it.