@feltdb/feltkit 0.3.11 → 0.3.13

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.
Files changed (146) hide show
  1. package/README.md +4 -3
  2. package/dist/app.d.ts +98 -3
  3. package/dist/app.js +63 -0
  4. package/dist/app.js.map +1 -1
  5. package/dist/appboundry/build.d.ts +39 -1
  6. package/dist/appboundry/build.js +57 -6
  7. package/dist/appboundry/build.js.map +1 -1
  8. package/dist/appboundry/guest.js +46 -5
  9. package/dist/appboundry/guest.js.map +1 -1
  10. package/dist/appboundry/host.d.ts +24 -5
  11. package/dist/appboundry/host.js +234 -141
  12. package/dist/appboundry/host.js.map +1 -1
  13. package/dist/appboundry/runtime.d.ts +44 -0
  14. package/dist/appboundry/runtime.js +99 -0
  15. package/dist/appboundry/runtime.js.map +1 -0
  16. package/dist/cli/entry.d.ts +1 -0
  17. package/dist/cli/entry.js +4 -0
  18. package/dist/cli/entry.js.map +1 -0
  19. package/dist/cli/main.d.ts +5 -0
  20. package/dist/cli/main.js +550 -13
  21. package/dist/cli/main.js.map +1 -1
  22. package/dist/cli/test-reporter.d.ts +9 -0
  23. package/dist/cli/test-reporter.js +26 -0
  24. package/dist/cli/test-reporter.js.map +1 -0
  25. package/dist/client/index.d.ts +3 -0
  26. package/dist/client/index.js +3 -0
  27. package/dist/client/index.js.map +1 -1
  28. package/dist/dashboard/assets/index-BSnW2DC-.js +15 -0
  29. package/dist/dashboard/assets/{index-91I1zDK-.css → index-BXTNQAg1.css} +1 -1
  30. package/dist/dashboard/index.html +3 -3
  31. package/dist/docs.d.ts +12 -0
  32. package/dist/docs.js +42 -0
  33. package/dist/docs.js.map +1 -0
  34. package/dist/errors.d.ts +15 -0
  35. package/dist/errors.js +9 -0
  36. package/dist/errors.js.map +1 -1
  37. package/dist/index.d.ts +1 -1
  38. package/dist/index.js.map +1 -1
  39. package/dist/platform/changes.d.ts +340 -0
  40. package/dist/platform/changes.js +355 -0
  41. package/dist/platform/changes.js.map +1 -0
  42. package/dist/platform/deployments.d.ts +653 -0
  43. package/dist/platform/deployments.js +532 -0
  44. package/dist/platform/deployments.js.map +1 -0
  45. package/dist/platform/operations.d.ts +74 -0
  46. package/dist/platform/operations.js +198 -0
  47. package/dist/platform/operations.js.map +1 -0
  48. package/dist/platform/platform.d.ts +78 -0
  49. package/dist/platform/platform.js +264 -0
  50. package/dist/platform/platform.js.map +1 -0
  51. package/dist/platform/server.d.ts +25 -0
  52. package/dist/platform/server.js +165 -0
  53. package/dist/platform/server.js.map +1 -0
  54. package/dist/platform/source.d.ts +27 -0
  55. package/dist/platform/source.js +142 -0
  56. package/dist/platform/source.js.map +1 -0
  57. package/dist/runtime/activity.d.ts +25 -0
  58. package/dist/runtime/activity.js +38 -12
  59. package/dist/runtime/activity.js.map +1 -1
  60. package/dist/runtime/agent.d.ts +16 -0
  61. package/dist/runtime/agent.js +92 -28
  62. package/dist/runtime/agent.js.map +1 -1
  63. package/dist/runtime/backup-environment.d.ts +32 -0
  64. package/dist/runtime/backup-environment.js +92 -0
  65. package/dist/runtime/backup-environment.js.map +1 -0
  66. package/dist/runtime/backup.d.ts +129 -0
  67. package/dist/runtime/backup.js +344 -0
  68. package/dist/runtime/backup.js.map +1 -0
  69. package/dist/runtime/capabilities.js +4 -2
  70. package/dist/runtime/capabilities.js.map +1 -1
  71. package/dist/runtime/changes.js +2 -2
  72. package/dist/runtime/changes.js.map +1 -1
  73. package/dist/runtime/contract.js +4 -3
  74. package/dist/runtime/contract.js.map +1 -1
  75. package/dist/runtime/data.d.ts +36 -5
  76. package/dist/runtime/data.js +165 -55
  77. package/dist/runtime/data.js.map +1 -1
  78. package/dist/runtime/decisions.js +2 -1
  79. package/dist/runtime/decisions.js.map +1 -1
  80. package/dist/runtime/instance.js +17 -0
  81. package/dist/runtime/instance.js.map +1 -1
  82. package/dist/runtime/integrations.js +14 -6
  83. package/dist/runtime/integrations.js.map +1 -1
  84. package/dist/runtime/loader.js +28 -4
  85. package/dist/runtime/loader.js.map +1 -1
  86. package/dist/runtime/migration-context.d.ts +25 -0
  87. package/dist/runtime/migration-context.js +69 -0
  88. package/dist/runtime/migration-context.js.map +1 -0
  89. package/dist/runtime/outbox.d.ts +6 -82
  90. package/dist/runtime/outbox.js +14 -59
  91. package/dist/runtime/outbox.js.map +1 -1
  92. package/dist/runtime/readiness.js +18 -1
  93. package/dist/runtime/readiness.js.map +1 -1
  94. package/dist/runtime/runtime.d.ts +84 -8
  95. package/dist/runtime/runtime.js +372 -131
  96. package/dist/runtime/runtime.js.map +1 -1
  97. package/dist/runtime/services.d.ts +41 -5
  98. package/dist/runtime/services.js +49 -4
  99. package/dist/runtime/services.js.map +1 -1
  100. package/dist/runtime/sessions.js +4 -3
  101. package/dist/runtime/sessions.js.map +1 -1
  102. package/dist/runtime/state-contract.d.ts +167 -0
  103. package/dist/runtime/state-contract.js +438 -0
  104. package/dist/runtime/state-contract.js.map +1 -0
  105. package/dist/runtime/transactions.d.ts +199 -0
  106. package/dist/runtime/transactions.js +246 -0
  107. package/dist/runtime/transactions.js.map +1 -0
  108. package/dist/schema.d.ts +13 -1
  109. package/dist/schema.js +21 -2
  110. package/dist/schema.js.map +1 -1
  111. package/dist/server/admin.d.ts +3 -2
  112. package/dist/server/admin.js +62 -10
  113. package/dist/server/admin.js.map +1 -1
  114. package/dist/server/index.d.ts +6 -1
  115. package/dist/server/index.js +90 -9
  116. package/dist/server/index.js.map +1 -1
  117. package/dist/server/mcp.js +1 -1
  118. package/dist/server/mcp.js.map +1 -1
  119. package/dist/server/project.d.ts +5 -0
  120. package/dist/server/project.js +13 -2
  121. package/dist/server/project.js.map +1 -1
  122. package/dist/testing/index.d.ts +10 -3
  123. package/dist/testing/index.js +33 -7
  124. package/dist/testing/index.js.map +1 -1
  125. package/docs/AGENT-OPERATIONS.md +515 -0
  126. package/docs/APPBOUNDRY.md +240 -0
  127. package/docs/ARCHITECTURE.md +126 -0
  128. package/docs/BACKUP.md +115 -0
  129. package/docs/GUARANTEES.md +457 -0
  130. package/docs/PATH-TO-PRODUCTION.md +117 -0
  131. package/docs/README.md +15 -0
  132. package/docs/SECURITY.md +182 -0
  133. package/docs/TRANSACTIONS.md +216 -0
  134. package/docs/UPSTREAM-GAPS.md +270 -0
  135. package/docs/WHY-FELTKIT.md +64 -0
  136. package/docs/assets/feltkit-logo-dark.png +0 -0
  137. package/docs/assets/feltkit-logo.png +0 -0
  138. package/package.json +10 -8
  139. package/skills/.claude-plugin/marketplace.json +1 -1
  140. package/skills/.claude-plugin/plugin.json +3 -3
  141. package/skills/feltkit-agent/SKILL.md +9 -5
  142. package/skills/feltkit-build/SKILL.md +16 -4
  143. package/skills/feltkit-data/SKILL.md +20 -3
  144. package/skills/feltkit-services/SKILL.md +13 -7
  145. package/dist/dashboard/assets/index-BhFOquA7.js +0 -15
  146. package/dist/dashboard/theme.js +0 -11
package/dist/cli/main.js CHANGED
@@ -2,8 +2,10 @@
2
2
  * The `feltkit` command.
3
3
  */
4
4
  import { spawn } from "node:child_process";
5
- import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
6
- import { join, relative, resolve } from "node:path";
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
6
+ import { dirname, extname, join, relative, resolve } from "node:path";
7
+ import { createHash, randomUUID } from "node:crypto";
8
+ import { fileURLToPath } from "node:url";
7
9
  import { FeltKitError, isFeltKitError } from "../errors.js";
8
10
  import { resolveEnvironment } from "../runtime/environment.js";
9
11
  import { loadSources } from "../runtime/loader.js";
@@ -11,22 +13,40 @@ import { describeStorage } from "../runtime/environment.js";
11
13
  import { deploymentArtifact, productionEnv, readDeployment, writeDeployment } from "../runtime/deployment.js";
12
14
  import { readAdminToken, readRuntimeRecord } from "../runtime/projects.js";
13
15
  import { chooseRoles, defaultOwnerId, issueProductionSession, loadProjectFor, studioLink } from "../server/production.js";
16
+ import { blockedHint, describePlan } from "../runtime/state-contract.js";
17
+ import { fileSink, verifyBackupFile } from "../runtime/backup.js";
18
+ import { backupEnvironmentTo, restoreEnvironmentFile } from "../runtime/backup-environment.js";
14
19
  import { createGrant, operatorKey } from "../server/operators.js";
15
20
  import { assessReadiness } from "../runtime/readiness.js";
16
21
  import { EnvironmentCredentials, looksLikeSecret, toCredentialRef } from "../runtime/credentials.js";
17
22
  import { HOST_CUSTODY, credentialInventory, removeCredential, selectModel, storeCredential } from "../server/admin.js";
18
23
  import { FeltKitRuntime, silentLogger } from "../runtime/runtime.js";
19
24
  import { overviewPayload } from "../server/admin.js";
20
- import { SDK_VERSION, artifactEnv, build, codegen, doctor, startDev, startProduction } from "../server/project.js";
25
+ import { BUILD_DIR, SDK_VERSION, artifactEnv, build, codegen, doctor, startDev, startProduction } from "../server/project.js";
21
26
  import { scaffold, ScaffoldError } from "create-feltkit";
22
27
  import { DEPLOY_TARGETS, deploy, lower } from "./deploy.js";
23
28
  import { createInterface } from "node:readline/promises";
29
+ import { createInterface as createLineReader } from "node:readline";
30
+ import { Readable } from "node:stream";
24
31
  import { feltdbContract, formatContract } from "../runtime/contract.js";
25
32
  import { checkSkills, installSkills, shippedSkills, skillsTarget } from "./skills.js";
26
33
  import { c, line, printInspect, symbols } from "./output.js";
34
+ import { PACKAGE_PAGE, SHIPPED_DOCS, docFile, docUrl } from "../docs.js";
35
+ /** Flags that may be given more than once; their values are joined with commas (`--role a --role b` = `a,b`). */
36
+ const REPEATABLE = new Set(["role"]);
27
37
  export function parseArgs(argv) {
28
38
  const positional = [];
29
39
  const flags = {};
40
+ const set = (key, value) => {
41
+ const previous = flags[key];
42
+ if (previous !== undefined && typeof value === "string" && typeof previous === "string") {
43
+ if (!REPEATABLE.has(key))
44
+ throw new FeltKitError("INVALID_ARGUMENT", `--${key} was given more than once ("${previous}" and "${value}"); give it once.`);
45
+ flags[key] = `${previous},${value}`;
46
+ return;
47
+ }
48
+ flags[key] = value;
49
+ };
30
50
  for (let i = 0; i < argv.length; i++) {
31
51
  const arg = argv[i];
32
52
  if (arg === "--") {
@@ -36,13 +56,13 @@ export function parseArgs(argv) {
36
56
  if (arg.startsWith("--")) {
37
57
  const [key, inline] = arg.slice(2).split("=", 2);
38
58
  if (key.startsWith("no-"))
39
- flags[key.slice(3)] = false;
59
+ set(key.slice(3), false);
40
60
  else if (inline !== undefined)
41
- flags[key] = inline;
61
+ set(key, inline);
42
62
  else if (argv[i + 1] && !argv[i + 1].startsWith("-"))
43
- flags[key] = argv[++i];
63
+ set(key, argv[++i]);
44
64
  else
45
- flags[key] = true;
65
+ set(key, true);
46
66
  }
47
67
  else if (arg.startsWith("-") && arg.length > 1) {
48
68
  flags[arg.slice(1)] = true;
@@ -69,7 +89,12 @@ ${c.bold("Commands")}
69
89
  fly <action> Create the Fly.io app (and volume), set its secrets, deploy, and sign you in
70
90
  manage Open production Studio for the deployed app (a one-time sign-in link)
71
91
  session <action> Create, list, or revoke sessions (agents, service accounts)
92
+ op [<capability>] List or invoke FeltKit's development and operations capabilities
93
+ platform <action> Serve them to agents over AppPort and MCP; manage platform sessions
72
94
  operator grant Sign a one-time production Studio sign-in for an operator
95
+ migrate Review and apply schema changes (and app.migration()s) to the environment's data
96
+ outbox <action> List after-commit effects (ctx.afterCommit), or retry a failed one
97
+ backup <action> Create, verify, list, or restore an application backup (local state)
73
98
  readiness Check what this environment has and lacks before production
74
99
  model <action> Show or select the model that makes agent decisions
75
100
  credential <action> Store an API key or check where each credential comes from
@@ -78,6 +103,7 @@ ${c.bold("Commands")}
78
103
  contract Write the FeltDB application contract (for Managed FeltDB)
79
104
  doctor Check the project and installation for problems
80
105
  skills <action> Install, update, or check the FeltKit skills for coding agents
106
+ docs [<name>] List FeltKit's documentation (shipped in the package), or print one document
81
107
 
82
108
  ${c.bold("Options")}
83
109
  --port <n> Port for dev/start (default 3000)
@@ -85,12 +111,50 @@ ${c.bold("Options")}
85
111
  --json Machine-readable output (inspect, session, doctor)
86
112
  --help Show help for a command
87
113
 
88
- Docs: https://github.com/rkendel1/concave#readme`;
114
+ Docs: \`feltkit docs\` (shipped in node_modules/@feltdb/feltkit/docs) · ${PACKAGE_PAGE}`;
115
+ /**
116
+ * Help for `feltkit <command> [<action>] --help`: with an action the command's help documents
117
+ * (`feltkit credential remove …`), only that action's lines; otherwise the whole command.
118
+ */
119
+ export function helpFor(command, action) {
120
+ const text = COMMAND_HELP[command];
121
+ if (!text)
122
+ return HELP;
123
+ if (!action)
124
+ return text;
125
+ const blocks = [];
126
+ for (const row of text.split("\n")) {
127
+ if (row.startsWith("feltkit ") || !blocks.length)
128
+ blocks.push([row]);
129
+ else
130
+ blocks.at(-1).push(row);
131
+ }
132
+ const own = blocks.filter((b) => b[0].startsWith(`feltkit ${command} ${action}`));
133
+ return own.length ? own.map((b) => b.join("\n")).join("\n") : text;
134
+ }
89
135
  const COMMAND_HELP = {
136
+ docs: "feltkit docs List the documentation shipped with this install\n" +
137
+ "feltkit docs <name> Print one document (e.g. feltkit docs guarantees)\n" +
138
+ " Offline: the files are in node_modules/@feltdb/feltkit/docs. --json lists name, file and public URL.",
139
+ backup: "feltkit backup create [--env development] [--out <file>]\n" +
140
+ "feltkit backup verify <file>\n" +
141
+ "feltkit backup list [--dir .feltkit/backups]\n" +
142
+ "feltkit backup restore <file> --env <env>\n" +
143
+ " One application's state (feltkit.backup/1; `feltkit docs backup`): its contract, migration history, records,\n" +
144
+ " AppPort Services records and outbox; never sessions. `create` reads a running development server through\n" +
145
+ " its admin API (calls pause while it reads), else the stopped environment directly. `restore` writes only\n" +
146
+ " into a new, empty environment, after verifying the whole backup; an interrupted restore is refused at start.\n" +
147
+ " Local FeltDB state only: a FeltDB server's backups are `feltdb-server backup`.",
148
+ outbox: "feltkit outbox list [--state pending|performing|done|failed] [--env development] [--json]\n" +
149
+ "feltkit outbox retry <id> [--env development]\n" +
150
+ " After-commit effects (ctx.afterCommit) are recorded with the mutation and performed after it commits:\n" +
151
+ " done, or failed with the error. A failed effect is never retried on its own; `retry` moves it back to\n" +
152
+ " pending (attempts and last error kept) and performs it again as its caller. Delivery is at least once.",
90
153
  create: "feltkit create <dir> [--name <app-name>] [--template tasks|managed]\n Copies a starter into <dir>: tasks (default; local FeltDB) or managed (Managed FeltDB, --managed).\n Refuses to write into a non-empty directory.",
91
154
  dev: "feltkit dev [--port 3000] [--host 127.0.0.1] [--no-frontend]\n Development environment: state in .feltkit/development/state.",
92
- build: "feltkit build [--target appboundry] [--out <dir>]\n Writes .feltkit/build/functions.mjs and dist/client, then loads the bundle to verify it.\n --target appboundry also compiles <name>.app: manifest.json, module.wasm (imports nothing) and the\n frontend, which AppBoundry runs without this project, Node tooling, or FeltKit. Test the artifact itself\n with createArtifactTestApp(<name>.app) from @feltdb/feltkit/testing. Without --target, lists what would\n block the AppBoundry target.",
93
- start: "feltkit start [--port $PORT] [--host 0.0.0.0] [--env production]\n Uses FELTDB_URL + FELTDB_TOKEN when set, else FELTKIT_STATE_DIR or .feltkit/production/state.",
155
+ build: "feltkit build [--target appboundry] [--out <dir>]\n Writes .feltkit/build/functions.mjs and dist/client, then loads the bundle to verify it.\n --target appboundry also compiles <name>.app: manifest.json, module.wasm (imports nothing) and the\n frontend, which AppBoundry (@appport/appboundry 1.3.0 or later) runs without this project, Node tooling, or FeltKit. Test the artifact itself\n with createArtifactTestApp(<name>.app) from @feltdb/feltkit/testing. Without --target, lists what would\n block the AppBoundry target.",
156
+ start: "feltkit start [--port $PORT] [--host 0.0.0.0] [--env production] [--no-migrate]\n Uses FELTDB_URL + FELTDB_TOKEN when set, else FELTKIT_STATE_DIR or .feltkit/production/state.\n Installs the schema feltkit/ declares when FeltDB accepts it (with pending app.migration()s), and refuses\n to start when it would strand or violate stored records. --no-migrate (or FELTKIT_MIGRATE=manual): refuse\n to start on any schema change until `feltkit migrate` applies it.",
157
+ migrate: "feltkit migrate [--env development] [--dry-run] [--yes] [--json]\n Compares the schema your collections declare with the one installed in the environment's FeltDB,\n runs pending app.migration()s on a copy, checks every resulting record, and shows the plan. Then\n (after you confirm, or with --yes) applies it as one FeltDB transaction: the migrations' writes and the\n new schema together, or nothing. History: `feltkit migrate --history`. A FeltDB server or Managed\n FeltDB enforces the contract published to it instead (`feltkit contract`).",
94
158
  test: "feltkit test [files…]\n Runs node --test on tests/**/*.test.ts with FELTKIT_ENV=test.",
95
159
  inspect: "feltkit inspect [--json] [--env development]\n Reads from the running server when there is one; otherwise opens the environment directly.",
96
160
  contract: "feltkit contract [--out feltdb.contract.json] [--check]\n" +
@@ -181,6 +245,22 @@ const COMMAND_HELP = {
181
245
  " Signs a one-time grant with this environment's operator key (FELTKIT_OPERATOR_KEY from the environment or, for a\n" +
182
246
  " deployment, .env.local; else .feltkit/<env>/operator-key). With a recorded deployment it prints a link that signs\n" +
183
247
  " in with it; otherwise paste it into Studio. It becomes an operator session holding exactly these declared roles.",
248
+ op: "feltkit op [list] [--json]\n" +
249
+ " FeltKit's development and operations capabilities (application dev.feltkit.platform; `feltkit docs agent-operations`):\n" +
250
+ " each with its typed input, effect and the permission it requires.\n" +
251
+ "feltkit op <capability> --input '<json>' [--project <dir>] [--root <dir>] [--json]\n" +
252
+ " Invokes one as the workspace owner, through the same AppPort application agents use over /appport and /mcp\n" +
253
+ " (via the running `feltkit platform serve` for that root, else in process). `project` is relative to --root\n" +
254
+ " (default: the current directory). Every invocation is recorded with its decision id. Exit code 1 when refused or failed.",
255
+ platform: "feltkit platform serve [--root <dir>] [--port <n>] [--host 127.0.0.1]\n" +
256
+ " Serves the platform's capabilities over AppPort (/appport, /appport/manifest) and MCP (/mcp) for the projects\n" +
257
+ " under --root. Every request carries a platform session; it is checked on every call, so a revoked one stops at\n" +
258
+ " its next request. MCP lists only the tools the session's profile grants.\n" +
259
+ "feltkit platform session create --id <id> --profile inspect|develop|deploy:<project>/<environment>|owner [--type agent|user|service] [--ttl <hours>] [--label <text>] [--json]\n" +
260
+ "feltkit platform session list [--json]\n" +
261
+ "feltkit platform session revoke <ref> | --principal <id>\n" +
262
+ " Profiles: inspect (feltkit.platform.read), develop (+ feltkit.platform.develop: propose and verify change sets),\n" +
263
+ " deploy:<project>/<environment> (+ apply change sets to that project and environment only), owner (everything).",
184
264
  session: "feltkit session create --id <id> --role <role> [--type agent|user|service] [--label <text>] [--ttl <hours>] [--env development]\n" +
185
265
  " --env production acts on what the deployment uses: for a Vercel or other FeltDB-backed deployment, its FeltDB,\n" +
186
266
  " with the settings in .env.local (refused when they are missing, never this machine's .feltkit/production).\n" +
@@ -194,6 +274,30 @@ async function adminRequest(record, token, path, init = {}) {
194
274
  throw new FeltKitError(body?.error?.code ?? "INTERNAL", body?.error?.message ?? `Admin API answered ${response.status}`);
195
275
  return body;
196
276
  }
277
+ /** A running server's backup (POST /backup, NDJSON), passed line by line to `sink`. Returns its header. */
278
+ async function adminBackup(record, token, sink) {
279
+ const response = await fetch(`${record.url}/_feltkit/api/backup`, { method: "POST", headers: { "x-feltkit-admin": token, "Content-Type": "application/json" } });
280
+ if (!response.ok || !response.body) {
281
+ const body = (await response.json().catch(() => null));
282
+ throw new FeltKitError(body?.error?.code ?? "INTERNAL", body?.error?.message ?? `Admin API answered ${response.status}`);
283
+ }
284
+ let header = null;
285
+ const lines = createLineReader({ input: Readable.fromWeb(response.body), crlfDelay: Infinity });
286
+ for await (const text of lines) {
287
+ if (!text)
288
+ continue;
289
+ if (header === null)
290
+ header = JSON.parse(text);
291
+ else if (text.startsWith('{"error":')) {
292
+ const { error } = JSON.parse(text);
293
+ throw new FeltKitError((error?.code ?? "INTERNAL"), `The server stopped the backup: ${error?.message ?? "unknown error"}`);
294
+ }
295
+ await sink(text);
296
+ }
297
+ if (header === null)
298
+ throw new FeltKitError("INTERNAL", "The server's backup was empty.");
299
+ return header;
300
+ }
197
301
  /** Use the running server for an environment if there is one; otherwise open the environment directly. */
198
302
  async function withEnvironment(projectDir, envName, remote, local) {
199
303
  const runtimeDir = join(projectDir, ".feltkit", envName);
@@ -214,7 +318,8 @@ async function withEnvironment(projectDir, envName, remote, local) {
214
318
  const env = envName === "production" ? productionEnv(projectDir) : artifactEnv(projectDir);
215
319
  const project = await loadProjectFor(projectDir, envName);
216
320
  const environment = resolveEnvironment({ projectDir, appName: project.app.name, name: envName, env });
217
- const runtime = await FeltKitRuntime.start({ project, environment, env, logger: silentLogger });
321
+ // Opened to read (or to migrate explicitly): never change the schema as a side effect.
322
+ const runtime = await FeltKitRuntime.start({ project, environment, env, logger: silentLogger, migrate: "off" });
218
323
  const storage = describeStorage(environment.storage);
219
324
  const where = storage.kind === "remote" ? `the FeltDB at ${storage.location}` : `local state in ${relative(process.cwd(), storage.location) || storage.location}`;
220
325
  try {
@@ -314,7 +419,7 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
314
419
  return 0;
315
420
  }
316
421
  if (flags.help || flags.h) {
317
- line(COMMAND_HELP[command] ?? HELP);
422
+ line(helpFor(command, positional[0]));
318
423
  return 0;
319
424
  }
320
425
  if (command === "--version" || command === "version" || flags.version) {
@@ -369,6 +474,28 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
369
474
  line(c.dim("Publish it to Managed FeltDB with `npx feltdb publish --contract " + (flags.out ?? "feltdb.contract.json") + " --yes`."));
370
475
  return 0;
371
476
  }
477
+ case "docs": {
478
+ const wanted = positional[0]?.toUpperCase().replace(/\.MD$/, "");
479
+ if (!wanted) {
480
+ if (json)
481
+ line(JSON.stringify(SHIPPED_DOCS.map(([name, what]) => ({ name, what, file: docFile(name), url: docUrl(name) })), null, 2));
482
+ else {
483
+ line(`${c.bold("FeltKit documentation")} ${c.dim(SDK_VERSION)}, shipped in this install. \`feltkit docs <name>\` prints one.\n`);
484
+ for (const [name, what] of SHIPPED_DOCS)
485
+ line(` ${name.replace(/\.md$/, "").toLowerCase().padEnd(20)} ${what}`);
486
+ line(`\n${c.dim(`Files: ${dirname(docFile(SHIPPED_DOCS[0][0]))}`)}\n${c.dim(`Public: ${docUrl()} · ${PACKAGE_PAGE}`)}`);
487
+ }
488
+ return 0;
489
+ }
490
+ const doc = SHIPPED_DOCS.find(([name]) => name.replace(/\.md$/, "") === wanted);
491
+ if (!doc)
492
+ throw new FeltKitError("NOT_FOUND", `No document called "${positional[0]}".`, { hint: `Run \`feltkit docs\` for the list: ${SHIPPED_DOCS.map(([n]) => n.replace(/\.md$/, "").toLowerCase()).join(", ")}.` });
493
+ const file = docFile(doc[0]);
494
+ if (!existsSync(file))
495
+ throw new FeltKitError("CONFIGURATION", `${doc[0]} is not in this install (${file}).`, { hint: `Read it at ${docUrl(doc[0])}.` });
496
+ line(readFileSync(file, "utf8").replace(/\n$/, ""));
497
+ return 0;
498
+ }
372
499
  case "codegen": {
373
500
  const changed = codegen(projectDir);
374
501
  line(`${symbols.ok} feltkit/_generated/api.ts ${changed ? "updated" : "already up to date"}`);
@@ -417,15 +544,31 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
417
544
  line(` ${c.bold("AppPort")} ${dev.server.url}/appport ${c.dim(`(${overview.functions.filter((f) => f.capability).length + [...dev.runtime.app.integrations.values()].reduce((n, i) => n + Object.keys(i.operations).length, 0)} capabilities)`)}`);
418
545
  line(` ${c.bold("MCP")} ${dev.server.url}/mcp ${c.dim("(agents; needs a session from `feltkit session create --type agent`)")}`);
419
546
  line(` ${c.bold("State")} ${overview.instance.location} ${c.dim(`(FeltDB ${overview.instance.feltdbVersion}, ${overview.instance.mode})`)}`);
547
+ const schema = dev.runtime.schema;
548
+ if (schema) {
549
+ const v = schema.plan.declared.version;
550
+ line(schema.status === "current"
551
+ ? ` ${c.bold("Schema")} v${v} ${c.dim(`(FeltDB enforces it${schema.applied ? `; just applied: ${[...schema.applied.changes.map((x) => `${x.kind} ${x.path.replace(/^collections\./, "")}`), ...schema.applied.migrations.map((m) => `"${m}"`)].join(", ") || "installed"}` : ""})`)}`
552
+ : schema.status === "unmanaged"
553
+ ? ` ${c.bold("Schema")} ${c.dim("enforced by the FeltDB authority from the published contract")}`
554
+ : ` ${c.bold("Schema")} ${c.red(schema.status)} ${schema.plan.reason ?? ""} ${c.dim("→ npx feltkit migrate --dry-run")}`);
555
+ }
420
556
  line(` ${c.bold("Functions")} ${overview.functions.length} from feltkit/${overview.collections.length ? ` ${c.dim("collections:")} ${overview.collections.map((x) => x.name).join(", ")}` : ""}`);
421
557
  line(c.dim(`\n Ready in ${Date.now() - started}ms. Edit feltkit/*.ts to reload. Ctrl+C to stop.\n`));
422
558
  await waitForShutdown(() => dev.close());
423
559
  return 0;
424
560
  }
425
561
  case "build": {
562
+ if (json && flags.target === undefined) {
563
+ const result = await build(projectDir);
564
+ const digest = createHash("sha256").update(readFileSync(result.bundle)).digest("hex");
565
+ line(JSON.stringify({ ok: true, ...result, bundle: relative(projectDir, result.bundle), client: result.client ? relative(projectDir, result.client) : null, bundleSha256: `sha256:${digest}`, sdk: SDK_VERSION }, null, 2));
566
+ return 0;
567
+ }
426
568
  line(`${c.bold("feltkit build")} ${c.dim(SDK_VERSION)}`);
427
569
  const result = await build(projectDir);
428
570
  line(`${symbols.ok} Backend ${result.bundle.replace(projectDir + "/", "")} ${c.dim(`(${result.functions} functions, ${result.capabilities} capabilities, verified by loading the bundle)`)}`);
571
+ line(`${symbols.ok} Schema ${result.collections} collection(s) compile to a FeltDB state contract ${c.dim(`(${result.schemaHash.slice(0, 19)}…; installed at start, or \`feltkit migrate\`)`)}`);
429
572
  line(result.client ? `${symbols.ok} Frontend ${result.client.replace(projectDir + "/", "")} ${c.dim("(scanned: no server-only values)")}` : `${symbols.info} No frontend (no index.html)`);
430
573
  if (flags.target !== undefined) {
431
574
  if (String(flags.target) !== "appboundry")
@@ -440,7 +583,28 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
440
583
  line(` ${symbols.info} ${c.dim(`Not in the artifact: ${note}`)}`);
441
584
  const relativeArtifact = artifact.path.replace(projectDir + "/", "");
442
585
  line(c.dim(`\nTest it: createArtifactTestApp("${relativeArtifact}") from @feltdb/feltkit/testing runs your calls against the artifact.`));
443
- line(c.dim(`Serve it with AppBoundry (built from github.com/rkendel1/appboundry; no npm release reads appboundry.app/1 yet): appboundry run ${relativeArtifact}`));
586
+ const { APPBOUNDRY_PACKAGE, MINIMUM_APPBOUNDRY, appboundryProblems, installHint, probeAppBoundry } = await import("../appboundry/runtime.js");
587
+ line(c.dim(`Serve it with AppBoundry ${MINIMUM_APPBOUNDRY} or later: npx ${APPBOUNDRY_PACKAGE}@^${MINIMUM_APPBOUNDRY} run ${relativeArtifact}`));
588
+ // An AppBoundry installed in this project must be able to run what was just built.
589
+ const installed = join(projectDir, "node_modules", ...APPBOUNDRY_PACKAGE.split("/"), "dist", "bin.js");
590
+ if (existsSync(installed)) {
591
+ let problems;
592
+ let version = "";
593
+ try {
594
+ const report = probeAppBoundry(installed);
595
+ version = report.version;
596
+ problems = appboundryProblems(report, m);
597
+ }
598
+ catch (error) {
599
+ problems = [error.message];
600
+ }
601
+ if (problems.length) {
602
+ line(`${symbols.fail} The ${APPBOUNDRY_PACKAGE}${version ? ` ${version}` : ""} installed in this project cannot run it: ${problems.join("; ")}`);
603
+ line(c.dim(` ${installHint()}`));
604
+ return 1;
605
+ }
606
+ line(`${symbols.ok} ${APPBOUNDRY_PACKAGE} ${version} installed in this project runs it`);
607
+ }
444
608
  return 0;
445
609
  }
446
610
  // Not an error: a FeltKit server runs all of it. Said now so a team learns before relying on the artifact target.
@@ -459,6 +623,7 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
459
623
  const server = await startProduction({
460
624
  projectDir,
461
625
  environment: envName,
626
+ ...(flags.migrate === false || process.env.FELTKIT_MIGRATE === "manual" ? { migrate: "manual" } : {}),
462
627
  ...(flags.port ? { port: Number(flags.port) } : {}),
463
628
  ...(flags.host ? { host: String(flags.host) } : {}),
464
629
  });
@@ -477,6 +642,34 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
477
642
  return 0;
478
643
  }
479
644
  const tsx = import.meta.resolve("tsx");
645
+ if (json) {
646
+ // One JSON report: each test with its outcome and, for a failure, what it expected and got.
647
+ const reporter = fileURLToPath(new URL(`./test-reporter${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
648
+ const { code, stdout, stderr } = await new Promise((done) => {
649
+ const child = spawn(process.execPath, ["--import", tsx, "--test", "--test-concurrency=1", `--test-reporter=${reporter}`, "--test-reporter-destination=stdout", ...files], {
650
+ cwd: projectDir,
651
+ stdio: ["ignore", "pipe", "pipe"],
652
+ env: { ...Object.fromEntries(Object.entries(process.env).filter(([k]) => k !== "NODE_TEST_CONTEXT")), FELTKIT_ENV: "test", FELTKIT_NO_REGISTRY: "1" },
653
+ });
654
+ let out = "";
655
+ let err = "";
656
+ child.stdout.on("data", (d) => (out += d));
657
+ child.stderr.on("data", (d) => (err += d));
658
+ child.on("exit", (status) => done({ code: status ?? 1, stdout: out, stderr: err }));
659
+ });
660
+ const tests = stdout.split("\n").filter((l) => l.startsWith("{")).map((l) => JSON.parse(l));
661
+ const report = {
662
+ ok: code === 0,
663
+ passed: tests.filter((t) => t.ok && !t.skipped).length,
664
+ failed: tests.filter((t) => !t.ok).length,
665
+ skipped: tests.filter((t) => t.skipped).length,
666
+ files: files.map((f) => relative(projectDir, resolve(projectDir, f))),
667
+ tests: tests.map((t) => ({ ...t, file: t.file ? relative(projectDir, t.file.startsWith("file:") ? fileURLToPath(t.file) : t.file) : null })),
668
+ ...(code !== 0 && !tests.some((t) => !t.ok) ? { error: stderr.slice(-4000) || `node --test exited with ${code}` } : {}),
669
+ };
670
+ line(JSON.stringify(report, null, 2));
671
+ return code;
672
+ }
480
673
  const code = await new Promise((done) => {
481
674
  const child = spawn(process.execPath, ["--import", tsx, "--test", "--test-concurrency=1", ...files], {
482
675
  cwd: projectDir,
@@ -488,6 +681,208 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
488
681
  });
489
682
  return code;
490
683
  }
684
+ case "migrate": {
685
+ if (flags.history) {
686
+ const { value, source } = await withEnvironment(projectDir, envName, (record, token) => adminRequest(record, token, "/schema"), async (runtime) => ({ history: await runtime.schemaHistory() }));
687
+ const history = value.history;
688
+ if (json)
689
+ line(JSON.stringify({ source, history }, null, 2));
690
+ else {
691
+ line(c.dim(`From ${source}`));
692
+ if (!history.length)
693
+ line(`${symbols.info} No schema changes recorded in ${envName}.`);
694
+ for (const h of history)
695
+ line(`${symbols.ok} v${h.to.version} ${h.appliedAt} ${c.dim(h.by)} ${h.changes.length} change(s)${h.migrations.length ? `, ${h.migrations.map((m) => `"${m}"`).join(", ")}` : ""}`);
696
+ }
697
+ return 0;
698
+ }
699
+ const { value: planned, source } = await withEnvironment(projectDir, envName, async (record, token) => (await adminRequest(record, token, "/schema")).plan, async (runtime) => runtime.schemaPlan());
700
+ const plan = planned;
701
+ if (!json) {
702
+ line(c.dim(`From ${source}`));
703
+ for (const text of describePlan(plan))
704
+ line(text);
705
+ }
706
+ if (plan.status === "current") {
707
+ if (json)
708
+ line(JSON.stringify({ source, plan, applied: null }, null, 2));
709
+ return 0;
710
+ }
711
+ if (plan.status === "unmanaged" || plan.status === "blocked") {
712
+ if (json)
713
+ line(JSON.stringify({ source, plan, applied: null }, null, 2));
714
+ else if (plan.status === "blocked")
715
+ line(`${symbols.fail} ${plan.reason}\n ${c.dim(blockedHint(plan))}`);
716
+ return 1;
717
+ }
718
+ if (flags["dry-run"]) {
719
+ if (json)
720
+ line(JSON.stringify({ source, plan, applied: null, dryRun: true }, null, 2));
721
+ else
722
+ line(c.dim("\nDry run: nothing was changed."));
723
+ return 0;
724
+ }
725
+ if (!flags.yes) {
726
+ if (!process.stdin.isTTY)
727
+ throw new FeltKitError("INVALID_ARGUMENT", "Applying a schema change needs confirmation: run it in a terminal, or pass --yes.", { hint: "Review the plan with `feltkit migrate --dry-run` first." });
728
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
729
+ const answer = (await rl.question(`Apply to ${envName}? [y/N] `)).trim().toLowerCase();
730
+ rl.close();
731
+ if (answer !== "y" && answer !== "yes") {
732
+ line(c.dim("Nothing was changed."));
733
+ return 1;
734
+ }
735
+ }
736
+ const by = `feltkit migrate (${defaultOwnerId()})`;
737
+ const { value: result } = await withEnvironment(projectDir, envName, async (record, token) => (await adminRequest(record, token, "/schema/migrate", { method: "POST", body: JSON.stringify({ by }) })).applied, async (runtime) => runtime.migrateSchema({ by }));
738
+ const applied = result;
739
+ if (json)
740
+ line(JSON.stringify({ source, plan, applied }, null, 2));
741
+ else if (applied)
742
+ line(`${symbols.ok} Schema ${applied.from ? `v${applied.from.version}` : "none"} → v${applied.to.version} applied in ${envName}${applied.migrations.length ? ` with ${applied.migrations.length} migration(s)` : ""}. FeltDB checked every record.`);
743
+ else
744
+ line(`${symbols.info} Nothing to apply.`);
745
+ return 0;
746
+ }
747
+ case "backup": {
748
+ const action = positional[0];
749
+ const project = async () => loadProjectFor(projectDir, envName);
750
+ const environmentFor = async () => {
751
+ const env = envName === "production" ? productionEnv(projectDir) : artifactEnv(projectDir);
752
+ const loaded = await project();
753
+ return { app: loaded.app, environment: resolveEnvironment({ projectDir, appName: loaded.app.name, name: envName, env }) };
754
+ };
755
+ if (action === "create") {
756
+ const runtimeDir = join(projectDir, ".feltkit", envName);
757
+ const record = readRuntimeRecord(runtimeDir);
758
+ // Written line by line to a partial file beside its destination, verified from disk, then renamed.
759
+ const explicit = typeof flags.out === "string" ? resolve(flags.out) : null;
760
+ if (explicit && existsSync(explicit))
761
+ throw new FeltKitError("CONFLICT", `${explicit} exists; a backup never overwrites a file.`);
762
+ const partial = explicit ? `${explicit}.partial` : join(projectDir, ".feltkit", "backups", envName, `.backup-${randomUUID()}.partial`);
763
+ mkdirSync(dirname(partial), { recursive: true });
764
+ let header;
765
+ let source;
766
+ const file = fileSink(partial);
767
+ try {
768
+ if (record) {
769
+ if (envName === "production")
770
+ throw new FeltKitError("CONFIGURATION", `A production server is running (pid ${record.pid}); its admin API answers verified operators only. Stop it to back up its state directly.`);
771
+ const token = readAdminToken(runtimeDir);
772
+ if (!token)
773
+ throw new FeltKitError("CONFIGURATION", `A ${envName} server is running (pid ${record.pid}) but its admin token is missing.`);
774
+ header = await adminBackup(record, token, file.sink);
775
+ source = `running server (pid ${record.pid}; calls paused while it read)`;
776
+ }
777
+ else {
778
+ const { app, environment } = await environmentFor();
779
+ header = await backupEnvironmentTo(environment, app, file.sink);
780
+ source = "the stopped environment, directly";
781
+ }
782
+ await file.close();
783
+ await verifyBackupFile(partial);
784
+ }
785
+ catch (error) {
786
+ await file.close().catch(() => undefined);
787
+ rmSync(partial, { force: true });
788
+ throw error;
789
+ }
790
+ const out = explicit ?? join(dirname(partial), `${header.application.name}-${header.createdAt.replace(/[:.]/g, "-")}.ndjson`);
791
+ if (existsSync(out)) {
792
+ rmSync(partial, { force: true });
793
+ throw new FeltKitError("CONFLICT", `${out} exists; a backup never overwrites a file.`);
794
+ }
795
+ renameSync(partial, out);
796
+ if (json)
797
+ line(JSON.stringify({ path: out, source, header }, null, 2));
798
+ else
799
+ line(`${symbols.ok} Backup of ${header.application.name} (${envName}) from ${source}: ${relative(process.cwd(), out) || out}\n ${header.collections.reduce((n, c) => n + c.records, 0)} records in ${header.collections.length} collections; contract ${header.contract ? `${header.contract.name} v${header.contract.version}` : "none"}; ${header.migrations.length} migration(s) applied. Verified.`);
800
+ return 0;
801
+ }
802
+ if (action === "verify") {
803
+ const file = positional[1];
804
+ if (!file)
805
+ throw new FeltKitError("INVALID_ARGUMENT", "Usage: feltkit backup verify <file>");
806
+ const { header, records } = await verifyBackupFile(resolve(file));
807
+ if (json)
808
+ line(JSON.stringify({ ok: true, header, records }, null, 2));
809
+ else
810
+ line(`${symbols.ok} ${file}: ${header.application.name} ${header.application.version} (${header.environment}, ${header.createdAt}); ${records} records; contract ${header.contract ? `${header.contract.name} v${header.contract.version} ${header.contract.hash.slice(0, 19)}…` : "none"}; FeltKit ${header.feltkit}, FeltDB ${header.feltdb}.`);
811
+ return 0;
812
+ }
813
+ if (action === "list") {
814
+ const dir = resolve(typeof flags.dir === "string" ? flags.dir : join(projectDir, ".feltkit", "backups"));
815
+ const files = existsSync(dir) ? readdirSync(dir, { recursive: true, withFileTypes: true }).filter((e) => e.isFile() && e.name.endsWith(".ndjson")).map((e) => join(e.parentPath ?? e.path ?? dir, e.name)).sort() : [];
816
+ const items = await Promise.all(files.map(async (path) => {
817
+ try {
818
+ const { header, records } = await verifyBackupFile(path);
819
+ return { path, ok: true, application: header.application, environment: header.environment, createdAt: header.createdAt, contract: header.contract ? { version: header.contract.version, hash: header.contract.hash } : null, records };
820
+ }
821
+ catch (error) {
822
+ return { path, ok: false, error: error.message };
823
+ }
824
+ }));
825
+ if (json)
826
+ line(JSON.stringify({ dir, items }, null, 2));
827
+ else if (!items.length)
828
+ line(`${symbols.info} No backups in ${relative(process.cwd(), dir) || dir}.`);
829
+ else
830
+ for (const i of items)
831
+ line(i.ok ? ` ${symbols.ok} ${relative(process.cwd(), i.path)} ${i.application.name} ${i.environment} ${i.createdAt} ${i.records} records contract ${i.contract ? `v${i.contract.version}` : "none"}` : ` ${symbols.fail} ${relative(process.cwd(), i.path)} ${i.error}`);
832
+ return items.every((i) => i.ok) ? 0 : 1;
833
+ }
834
+ if (action === "restore") {
835
+ const file = positional[1];
836
+ if (!file)
837
+ throw new FeltKitError("INVALID_ARGUMENT", "Usage: feltkit backup restore <file> --env <env>");
838
+ if (readRuntimeRecord(join(projectDir, ".feltkit", envName)))
839
+ throw new FeltKitError("CONFLICT", `A ${envName} server is running; a restore writes only into a new, empty environment. Nothing was written.`);
840
+ const { app, environment } = await environmentFor();
841
+ const { header, records } = await restoreEnvironmentFile(resolve(file), environment, app);
842
+ if (json)
843
+ line(JSON.stringify({ restored: true, environment: envName, header, records }, null, 2));
844
+ else
845
+ line(`${symbols.ok} Restored ${header.application.name} (${records} records, contract ${header.contract ? `v${header.contract.version}` : "none"}) into ${envName}. Sessions are not in a backup: issue new ones.`);
846
+ return 0;
847
+ }
848
+ line(COMMAND_HELP.backup);
849
+ return 1;
850
+ }
851
+ case "outbox": {
852
+ const action = positional[0] ?? "list";
853
+ if (action === "list") {
854
+ const state = typeof flags.state === "string" ? flags.state : undefined;
855
+ if (state && !["pending", "performing", "done", "failed"].includes(state))
856
+ throw new FeltKitError("INVALID_ARGUMENT", "--state is pending, performing, done or failed.");
857
+ const { value, source } = await withEnvironment(projectDir, envName, (record, token) => adminRequest(record, token, `/outbox${state ? `?state=${state}` : ""}`).then((b) => b.items), (runtime) => runtime.listOutbox(state ? { state: state } : {}));
858
+ if (json)
859
+ line(JSON.stringify({ source, items: value }, null, 2));
860
+ else {
861
+ line(c.dim(`From ${source}`));
862
+ if (!value.length)
863
+ line(`${symbols.info} No after-commit effects${state ? ` in state ${state}` : ""} in ${envName}.`);
864
+ for (const r of value) {
865
+ const effect = r.effect.service === "notifications" ? `notifications.send ${r.effect.input.type}` : `${r.effect.service}.${r.effect.method} ${r.effect.type}`;
866
+ line(` ${r.state === "failed" ? symbols.fail : r.state === "done" ? symbols.ok : symbols.info} ${r.id} ${r.state.padEnd(10)} ${effect} ${c.dim(`${r.function} as ${r.principalId}, ${r.attempts} attempt(s)`)}${r.error ? `\n ${r.error.code}: ${r.error.message}` : ""}`);
867
+ }
868
+ }
869
+ return 0;
870
+ }
871
+ if (action === "retry") {
872
+ const id = positional[1];
873
+ if (!id)
874
+ throw new FeltKitError("INVALID_ARGUMENT", "Usage: feltkit outbox retry <id> (see `feltkit outbox list --state failed`)");
875
+ const by = `feltkit outbox retry (${defaultOwnerId()})`;
876
+ const { value } = await withEnvironment(projectDir, envName, (record, token) => adminRequest(record, token, `/outbox/${encodeURIComponent(id)}/retry`, { method: "POST", body: JSON.stringify({ by }) }).then((b) => b.item), (runtime) => runtime.retryOutbox(id, by));
877
+ if (json)
878
+ line(JSON.stringify(value, null, 2));
879
+ else
880
+ line(value.state === "done" ? `${symbols.ok} ${id} performed (attempt ${value.attempts}).` : `${value.state === "failed" ? symbols.fail : symbols.info} ${id} is ${value.state}${value.error ? `: ${value.error.code}: ${value.error.message}` : ""}.`);
881
+ return value.state === "failed" ? 1 : 0;
882
+ }
883
+ line(COMMAND_HELP.outbox);
884
+ return 1;
885
+ }
491
886
  case "inspect": {
492
887
  const { value, source } = await withEnvironment(projectDir, envName, (record, token) => adminRequest(record, token, "/overview"), async (runtime) => overviewPayload(runtime));
493
888
  if (json)
@@ -511,6 +906,13 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
511
906
  throw new FeltKitError("INVALID_ARGUMENT", `Answer 1-${choices.length}.`);
512
907
  }
513
908
  const result = await deploy({ projectDir, ...(flags.out ? { out: String(flags.out) } : {}), ...(target ? { target: target } : {}), ...(flags.data ? { data: String(flags.data) } : {}), ...(flags.instances !== undefined ? { instances: Number(flags.instances) } : {}) });
909
+ if (json) {
910
+ // What a caller (the platform's change.apply) can rely on: deploy() returns only after the
911
+ // production build booted against isolated state and answered its health and capability checks.
912
+ const bundle = join(result.dir, BUILD_DIR, "functions.mjs");
913
+ line(JSON.stringify({ ok: true, dir: relative(projectDir, result.dir) || ".", target: result.target, application: result.application, storage: result.storage, bundleSha256: existsSync(bundle) ? `sha256:${createHash("sha256").update(readFileSync(bundle)).digest("hex")}` : null, schemaHash: result.build.schemaHash, health: { check: "boot", state: "isolated", passed: true }, sdk: SDK_VERSION }, null, 2));
914
+ return 0;
915
+ }
514
916
  line(`${symbols.ok} Built and verified: the production build booted against a temporary state directory and answered health and capability checks.`);
515
917
  line(`${symbols.ok} Artifact (${lower(DEPLOY_TARGETS[result.target])}): ${c.bold(result.dir)}${flags.out ? "" : c.dim(` (replaced on every deploy; its .feltkit/production state${result.target === "vercel" ? " and Vercel project link are" : " is"} kept)`)}`);
516
918
  // Paths relative to where the command ran, one command per line, so each can be pasted.
@@ -999,6 +1401,141 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
999
1401
  }
1000
1402
  return 0;
1001
1403
  }
1404
+ case "op": {
1405
+ // FeltKit's development and operations capabilities (docs/AGENT-OPERATIONS.md), as the
1406
+ // workspace owner: through the running `platform serve` when there is one, else in process.
1407
+ const root = resolve(String(flags.root ?? process.cwd()));
1408
+ const { OPERATIONS } = await import("../platform/operations.js");
1409
+ const name = positional[0];
1410
+ if (!name || name === "list") {
1411
+ const catalog = OPERATIONS.map((op) => ({ name: op.name, version: op.version, effect: op.effect, permission: op.permission, description: op.description, input: op.input.toJSONSchema(), approval: op.integration.approval }));
1412
+ if (json)
1413
+ line(JSON.stringify({ application: "dev.feltkit.platform", operations: catalog }, null, 2));
1414
+ else
1415
+ for (const op of catalog)
1416
+ line(` ${c.bold(op.name.padEnd(16))} ${op.effect.padEnd(12)} ${c.dim(op.permission.padEnd(26))} ${op.description}`);
1417
+ return 0;
1418
+ }
1419
+ let input = {};
1420
+ try {
1421
+ input = flags.input ? JSON.parse(String(flags.input)) : {};
1422
+ }
1423
+ catch {
1424
+ throw new FeltKitError("INVALID_ARGUMENT", "--input must be JSON, e.g. --input '{\"project\":\"my-app\"}'");
1425
+ }
1426
+ if (flags.project && input && typeof input === "object")
1427
+ input.project = String(flags.project);
1428
+ const { runningPlatform } = await import("../platform/server.js");
1429
+ const running = runningPlatform(root);
1430
+ let result;
1431
+ if (running) {
1432
+ const response = await fetch(`${running.url}/appport`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${running.token}` }, body: JSON.stringify({ protocol: "appport/1", type: "request", requestId: `req_cli_${Date.now()}`, capability: { name, version: 1 }, input }) });
1433
+ const body = (await response.json());
1434
+ const decisionId = body.authorizationDecision?.decisionId ?? body.error?.details?.decisionId;
1435
+ result = { ok: body.ok, ...(body.ok ? { output: body.output } : { error: body.error }), ...(decisionId ? { decisionId } : {}) };
1436
+ }
1437
+ else {
1438
+ const { Platform, localOwner } = await import("../platform/platform.js");
1439
+ const platform = Platform.open(root);
1440
+ try {
1441
+ result = await platform.invoke(name, input, { principal: localOwner(), transport: "cli" });
1442
+ }
1443
+ finally {
1444
+ await platform.close();
1445
+ }
1446
+ }
1447
+ if (json)
1448
+ line(JSON.stringify(result, null, 2));
1449
+ else if (result.ok)
1450
+ line(JSON.stringify(result.output, null, 2));
1451
+ else
1452
+ line(`${symbols.fail} ${result.error?.code}: ${result.error?.message}${result.decisionId ? c.dim(` (decision ${result.decisionId})`) : ""}`);
1453
+ return result.ok ? 0 : 1;
1454
+ }
1455
+ case "platform": {
1456
+ const root = resolve(String(flags.root ?? process.cwd()));
1457
+ const action = positional[0];
1458
+ const { runningPlatform, servePlatform } = await import("../platform/server.js");
1459
+ if (action === "serve") {
1460
+ if (runningPlatform(root))
1461
+ throw new FeltKitError("INVALID_ARGUMENT", `A platform server is already running for ${root} (.feltkit-platform/server.json).`);
1462
+ const { Platform } = await import("../platform/platform.js");
1463
+ const platform = Platform.open(root);
1464
+ const served = await servePlatform(platform, { ...(flags.port ? { port: Number(flags.port) } : {}), ...(flags.host ? { host: String(flags.host) } : {}) });
1465
+ line(`${symbols.ok} FeltKit platform for ${c.bold(root)}`);
1466
+ line(` AppPort ${served.url}/appport ${c.dim(`(manifest ${served.url}/appport/manifest)`)}`);
1467
+ line(` MCP ${served.url}/mcp`);
1468
+ line(c.dim("Every request needs a platform session: `feltkit platform session create --id <agent> --profile inspect|develop`."));
1469
+ await waitForShutdown(async () => {
1470
+ await served.close();
1471
+ await platform.close();
1472
+ });
1473
+ return 0;
1474
+ }
1475
+ if (action === "session") {
1476
+ const sub = positional[1];
1477
+ const running = runningPlatform(root);
1478
+ const remote = async (path, init = {}) => {
1479
+ const response = await fetch(`${running.url}${path}`, { ...init, headers: { "content-type": "application/json", authorization: `Bearer ${running.token}` } });
1480
+ const body = (await response.json());
1481
+ if (!body.ok)
1482
+ throw new FeltKitError("INVALID_ARGUMENT", body.error?.message ?? `platform server answered ${response.status}`);
1483
+ return body;
1484
+ };
1485
+ const local = async (work) => {
1486
+ const { Platform } = await import("../platform/platform.js");
1487
+ const platform = Platform.open(root);
1488
+ try {
1489
+ return await work(platform);
1490
+ }
1491
+ finally {
1492
+ await platform.close();
1493
+ }
1494
+ };
1495
+ if (sub === "create") {
1496
+ if (!flags.id || !flags.profile)
1497
+ throw new FeltKitError("INVALID_ARGUMENT", "Usage: feltkit platform session create --id <id> --profile inspect|develop|deploy:<project>/<environment>|owner [--type agent]");
1498
+ const request = { id: String(flags.id), type: String(flags.type ?? "agent"), profile: String(flags.profile), ...(flags.ttl ? { ttlMs: Number(flags.ttl) * 3_600_000 } : {}), ...(flags.label ? { label: String(flags.label) } : {}) };
1499
+ const issued = running
1500
+ ? await remote("/platform/sessions", { method: "POST", body: JSON.stringify(request) })
1501
+ : await local(async (platform) => {
1502
+ const session = await platform.issue(request);
1503
+ return { token: session.id, ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) };
1504
+ });
1505
+ if (json)
1506
+ line(JSON.stringify({ token: issued.token, principal: { id: request.id, type: request.type, profile: request.profile }, ...(issued.expiresAt ? { expiresAt: issued.expiresAt } : {}) }, null, 2));
1507
+ else {
1508
+ line(`${symbols.ok} Platform session for ${c.bold(request.id)} (${request.type}, profile ${request.profile})`);
1509
+ line(`\n ${issued.token}\n`);
1510
+ line(c.dim("Shown once. Use it as `Authorization: Bearer <token>` against the platform's /appport and /mcp. Revoke with `feltkit platform session revoke`."));
1511
+ }
1512
+ return 0;
1513
+ }
1514
+ if (sub === "list") {
1515
+ const sessions = running ? (await remote("/platform/sessions")).sessions : await local((platform) => platform.sessions.list());
1516
+ if (json)
1517
+ line(JSON.stringify(sessions, null, 2));
1518
+ else if (!sessions.length)
1519
+ line(`${symbols.info} No active platform sessions.`);
1520
+ else
1521
+ for (const s of sessions)
1522
+ line(` ${c.dim(s.ref)} ${String(s.principal?.id ?? "?").padEnd(16)} ${String(s.principal?.type ?? "").padEnd(8)} ${(s.principal?.roles ?? []).join(",").padEnd(10)} ${c.dim(s.expiresAt ? `expires ${s.expiresAt}` : "no expiry")}`);
1523
+ return 0;
1524
+ }
1525
+ if (sub === "revoke") {
1526
+ const ref = positional[2] ?? (flags.principal ? `principal:${flags.principal}` : undefined);
1527
+ if (!ref)
1528
+ throw new FeltKitError("INVALID_ARGUMENT", "Usage: feltkit platform session revoke <ref> | --principal <id>");
1529
+ const revoked = running
1530
+ ? (await remote(`/platform/sessions/${encodeURIComponent(ref)}`, { method: "DELETE" })).revoked
1531
+ : await local((platform) => (ref.startsWith("principal:") ? platform.sessions.revokePrincipal(ref.slice("principal:".length)) : platform.sessions.revoke(ref)));
1532
+ line(revoked ? `${symbols.ok} Revoked ${revoked} session${revoked === 1 ? "" : "s"}` : `${symbols.fail} No session matches ${ref}`);
1533
+ return revoked ? 0 : 1;
1534
+ }
1535
+ }
1536
+ line(COMMAND_HELP.platform);
1537
+ return 1;
1538
+ }
1002
1539
  case "skills": {
1003
1540
  const action = positional[0];
1004
1541
  const target = skillsTarget({ projectDir, user: flags.user === true, ...(flags.dir ? { dir: String(flags.dir) } : {}) });