@feltdb/feltkit 0.3.11 → 0.3.12

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 (98) hide show
  1. package/dist/app.d.ts +80 -3
  2. package/dist/app.js +41 -0
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.d.ts +39 -1
  5. package/dist/appboundry/build.js +47 -4
  6. package/dist/appboundry/build.js.map +1 -1
  7. package/dist/appboundry/guest.js +46 -5
  8. package/dist/appboundry/guest.js.map +1 -1
  9. package/dist/appboundry/host.d.ts +24 -5
  10. package/dist/appboundry/host.js +234 -141
  11. package/dist/appboundry/host.js.map +1 -1
  12. package/dist/appboundry/runtime.d.ts +44 -0
  13. package/dist/appboundry/runtime.js +99 -0
  14. package/dist/appboundry/runtime.js.map +1 -0
  15. package/dist/cli/entry.d.ts +1 -0
  16. package/dist/cli/entry.js +4 -0
  17. package/dist/cli/entry.js.map +1 -0
  18. package/dist/cli/main.js +445 -7
  19. package/dist/cli/main.js.map +1 -1
  20. package/dist/cli/test-reporter.d.ts +9 -0
  21. package/dist/cli/test-reporter.js +26 -0
  22. package/dist/cli/test-reporter.js.map +1 -0
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.js.map +1 -1
  25. package/dist/platform/changes.d.ts +340 -0
  26. package/dist/platform/changes.js +353 -0
  27. package/dist/platform/changes.js.map +1 -0
  28. package/dist/platform/deployments.d.ts +653 -0
  29. package/dist/platform/deployments.js +530 -0
  30. package/dist/platform/deployments.js.map +1 -0
  31. package/dist/platform/operations.d.ts +74 -0
  32. package/dist/platform/operations.js +198 -0
  33. package/dist/platform/operations.js.map +1 -0
  34. package/dist/platform/platform.d.ts +78 -0
  35. package/dist/platform/platform.js +264 -0
  36. package/dist/platform/platform.js.map +1 -0
  37. package/dist/platform/server.d.ts +25 -0
  38. package/dist/platform/server.js +165 -0
  39. package/dist/platform/server.js.map +1 -0
  40. package/dist/platform/source.d.ts +27 -0
  41. package/dist/platform/source.js +142 -0
  42. package/dist/platform/source.js.map +1 -0
  43. package/dist/runtime/backup-environment.d.ts +25 -0
  44. package/dist/runtime/backup-environment.js +60 -0
  45. package/dist/runtime/backup-environment.js.map +1 -0
  46. package/dist/runtime/backup.d.ts +87 -0
  47. package/dist/runtime/backup.js +175 -0
  48. package/dist/runtime/backup.js.map +1 -0
  49. package/dist/runtime/contract.js +4 -3
  50. package/dist/runtime/contract.js.map +1 -1
  51. package/dist/runtime/data.d.ts +6 -2
  52. package/dist/runtime/data.js +29 -23
  53. package/dist/runtime/data.js.map +1 -1
  54. package/dist/runtime/instance.js +17 -0
  55. package/dist/runtime/instance.js.map +1 -1
  56. package/dist/runtime/loader.js +6 -2
  57. package/dist/runtime/loader.js.map +1 -1
  58. package/dist/runtime/migration-context.d.ts +25 -0
  59. package/dist/runtime/migration-context.js +69 -0
  60. package/dist/runtime/migration-context.js.map +1 -0
  61. package/dist/runtime/outbox.d.ts +6 -82
  62. package/dist/runtime/outbox.js +14 -59
  63. package/dist/runtime/outbox.js.map +1 -1
  64. package/dist/runtime/readiness.js +12 -0
  65. package/dist/runtime/readiness.js.map +1 -1
  66. package/dist/runtime/runtime.d.ts +60 -2
  67. package/dist/runtime/runtime.js +301 -116
  68. package/dist/runtime/runtime.js.map +1 -1
  69. package/dist/runtime/services.d.ts +22 -0
  70. package/dist/runtime/services.js +35 -0
  71. package/dist/runtime/services.js.map +1 -1
  72. package/dist/runtime/state-contract.d.ts +167 -0
  73. package/dist/runtime/state-contract.js +438 -0
  74. package/dist/runtime/state-contract.js.map +1 -0
  75. package/dist/runtime/transactions.d.ts +199 -0
  76. package/dist/runtime/transactions.js +246 -0
  77. package/dist/runtime/transactions.js.map +1 -0
  78. package/dist/schema.d.ts +13 -1
  79. package/dist/schema.js +21 -2
  80. package/dist/schema.js.map +1 -1
  81. package/dist/server/admin.d.ts +1 -0
  82. package/dist/server/admin.js +27 -0
  83. package/dist/server/admin.js.map +1 -1
  84. package/dist/server/index.d.ts +4 -0
  85. package/dist/server/index.js +45 -1
  86. package/dist/server/index.js.map +1 -1
  87. package/dist/server/project.d.ts +5 -0
  88. package/dist/server/project.js +13 -2
  89. package/dist/server/project.js.map +1 -1
  90. package/dist/testing/index.d.ts +4 -1
  91. package/dist/testing/index.js +5 -3
  92. package/dist/testing/index.js.map +1 -1
  93. package/package.json +3 -3
  94. package/skills/.claude-plugin/marketplace.json +1 -1
  95. package/skills/.claude-plugin/plugin.json +1 -1
  96. package/skills/feltkit-build/SKILL.md +6 -3
  97. package/skills/feltkit-data/SKILL.md +11 -0
  98. package/skills/feltkit-services/SKILL.md +6 -4
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, writeFileSync } from "node:fs";
6
+ import { dirname, extname, join, relative, resolve } from "node:path";
7
+ import { createHash } 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,13 +13,16 @@ 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 { verifyBackup } from "../runtime/backup.js";
18
+ import { backupEnvironment, restoreEnvironment } 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";
@@ -69,7 +74,12 @@ ${c.bold("Commands")}
69
74
  fly <action> Create the Fly.io app (and volume), set its secrets, deploy, and sign you in
70
75
  manage Open production Studio for the deployed app (a one-time sign-in link)
71
76
  session <action> Create, list, or revoke sessions (agents, service accounts)
77
+ op [<capability>] List or invoke FeltKit's development and operations capabilities
78
+ platform <action> Serve them to agents over AppPort and MCP; manage platform sessions
72
79
  operator grant Sign a one-time production Studio sign-in for an operator
80
+ migrate Review and apply schema changes (and app.migration()s) to the environment's data
81
+ outbox <action> List after-commit effects (ctx.afterCommit), or retry a failed one
82
+ backup <action> Create, verify, list, or restore an application backup (local state)
73
83
  readiness Check what this environment has and lacks before production
74
84
  model <action> Show or select the model that makes agent decisions
75
85
  credential <action> Store an API key or check where each credential comes from
@@ -87,10 +97,25 @@ ${c.bold("Options")}
87
97
 
88
98
  Docs: https://github.com/rkendel1/concave#readme`;
89
99
  const COMMAND_HELP = {
100
+ backup: "feltkit backup create [--env development] [--out <file>]\n" +
101
+ "feltkit backup verify <file>\n" +
102
+ "feltkit backup list [--dir .feltkit/backups]\n" +
103
+ "feltkit backup restore <file> --env <env>\n" +
104
+ " One application's state (feltkit.backup/1, docs/BACKUP.md): its contract, migration history, records,\n" +
105
+ " AppPort Services records and outbox; never sessions. `create` reads a running development server through\n" +
106
+ " its admin API (calls pause while it reads), else the stopped environment directly. `restore` writes only\n" +
107
+ " into a new, empty environment, after verifying the whole backup; an interrupted restore is refused at start.\n" +
108
+ " Local FeltDB state only: a FeltDB server's backups are `feltdb-server backup`.",
109
+ outbox: "feltkit outbox list [--state pending|performing|done|failed] [--env development] [--json]\n" +
110
+ "feltkit outbox retry <id> [--env development]\n" +
111
+ " After-commit effects (ctx.afterCommit) are recorded with the mutation and performed after it commits:\n" +
112
+ " done, or failed with the error. A failed effect is never retried on its own; `retry` moves it back to\n" +
113
+ " pending (attempts and last error kept) and performs it again as its caller. Delivery is at least once.",
90
114
  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
115
  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.",
116
+ 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.",
117
+ 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.",
118
+ 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
119
  test: "feltkit test [files…]\n Runs node --test on tests/**/*.test.ts with FELTKIT_ENV=test.",
95
120
  inspect: "feltkit inspect [--json] [--env development]\n Reads from the running server when there is one; otherwise opens the environment directly.",
96
121
  contract: "feltkit contract [--out feltdb.contract.json] [--check]\n" +
@@ -181,6 +206,22 @@ const COMMAND_HELP = {
181
206
  " Signs a one-time grant with this environment's operator key (FELTKIT_OPERATOR_KEY from the environment or, for a\n" +
182
207
  " deployment, .env.local; else .feltkit/<env>/operator-key). With a recorded deployment it prints a link that signs\n" +
183
208
  " in with it; otherwise paste it into Studio. It becomes an operator session holding exactly these declared roles.",
209
+ op: "feltkit op [list] [--json]\n" +
210
+ " FeltKit's development and operations capabilities (application dev.feltkit.platform, docs/AGENT-OPERATIONS.md):\n" +
211
+ " each with its typed input, effect and the permission it requires.\n" +
212
+ "feltkit op <capability> --input '<json>' [--project <dir>] [--root <dir>] [--json]\n" +
213
+ " Invokes one as the workspace owner, through the same AppPort application agents use over /appport and /mcp\n" +
214
+ " (via the running `feltkit platform serve` for that root, else in process). `project` is relative to --root\n" +
215
+ " (default: the current directory). Every invocation is recorded with its decision id. Exit code 1 when refused or failed.",
216
+ platform: "feltkit platform serve [--root <dir>] [--port <n>] [--host 127.0.0.1]\n" +
217
+ " Serves the platform's capabilities over AppPort (/appport, /appport/manifest) and MCP (/mcp) for the projects\n" +
218
+ " under --root. Every request carries a platform session; it is checked on every call, so a revoked one stops at\n" +
219
+ " its next request. MCP lists only the tools the session's profile grants.\n" +
220
+ "feltkit platform session create --id <id> --profile inspect|develop|deploy:<project>/<environment>|owner [--type agent|user|service] [--ttl <hours>] [--label <text>] [--json]\n" +
221
+ "feltkit platform session list [--json]\n" +
222
+ "feltkit platform session revoke <ref> | --principal <id>\n" +
223
+ " Profiles: inspect (feltkit.platform.read), develop (+ feltkit.platform.develop: propose and verify change sets),\n" +
224
+ " deploy:<project>/<environment> (+ apply change sets to that project and environment only), owner (everything).",
184
225
  session: "feltkit session create --id <id> --role <role> [--type agent|user|service] [--label <text>] [--ttl <hours>] [--env development]\n" +
185
226
  " --env production acts on what the deployment uses: for a Vercel or other FeltDB-backed deployment, its FeltDB,\n" +
186
227
  " with the settings in .env.local (refused when they are missing, never this machine's .feltkit/production).\n" +
@@ -214,7 +255,8 @@ async function withEnvironment(projectDir, envName, remote, local) {
214
255
  const env = envName === "production" ? productionEnv(projectDir) : artifactEnv(projectDir);
215
256
  const project = await loadProjectFor(projectDir, envName);
216
257
  const environment = resolveEnvironment({ projectDir, appName: project.app.name, name: envName, env });
217
- const runtime = await FeltKitRuntime.start({ project, environment, env, logger: silentLogger });
258
+ // Opened to read (or to migrate explicitly): never change the schema as a side effect.
259
+ const runtime = await FeltKitRuntime.start({ project, environment, env, logger: silentLogger, migrate: "off" });
218
260
  const storage = describeStorage(environment.storage);
219
261
  const where = storage.kind === "remote" ? `the FeltDB at ${storage.location}` : `local state in ${relative(process.cwd(), storage.location) || storage.location}`;
220
262
  try {
@@ -417,15 +459,31 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
417
459
  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
460
  line(` ${c.bold("MCP")} ${dev.server.url}/mcp ${c.dim("(agents; needs a session from `feltkit session create --type agent`)")}`);
419
461
  line(` ${c.bold("State")} ${overview.instance.location} ${c.dim(`(FeltDB ${overview.instance.feltdbVersion}, ${overview.instance.mode})`)}`);
462
+ const schema = dev.runtime.schema;
463
+ if (schema) {
464
+ const v = schema.plan.declared.version;
465
+ line(schema.status === "current"
466
+ ? ` ${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"}` : ""})`)}`
467
+ : schema.status === "unmanaged"
468
+ ? ` ${c.bold("Schema")} ${c.dim("enforced by the FeltDB authority from the published contract")}`
469
+ : ` ${c.bold("Schema")} ${c.red(schema.status)} ${schema.plan.reason ?? ""} ${c.dim("→ npx feltkit migrate --dry-run")}`);
470
+ }
420
471
  line(` ${c.bold("Functions")} ${overview.functions.length} from feltkit/${overview.collections.length ? ` ${c.dim("collections:")} ${overview.collections.map((x) => x.name).join(", ")}` : ""}`);
421
472
  line(c.dim(`\n Ready in ${Date.now() - started}ms. Edit feltkit/*.ts to reload. Ctrl+C to stop.\n`));
422
473
  await waitForShutdown(() => dev.close());
423
474
  return 0;
424
475
  }
425
476
  case "build": {
477
+ if (json && flags.target === undefined) {
478
+ const result = await build(projectDir);
479
+ const digest = createHash("sha256").update(readFileSync(result.bundle)).digest("hex");
480
+ 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));
481
+ return 0;
482
+ }
426
483
  line(`${c.bold("feltkit build")} ${c.dim(SDK_VERSION)}`);
427
484
  const result = await build(projectDir);
428
485
  line(`${symbols.ok} Backend ${result.bundle.replace(projectDir + "/", "")} ${c.dim(`(${result.functions} functions, ${result.capabilities} capabilities, verified by loading the bundle)`)}`);
486
+ 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
487
  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
488
  if (flags.target !== undefined) {
431
489
  if (String(flags.target) !== "appboundry")
@@ -440,7 +498,28 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
440
498
  line(` ${symbols.info} ${c.dim(`Not in the artifact: ${note}`)}`);
441
499
  const relativeArtifact = artifact.path.replace(projectDir + "/", "");
442
500
  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}`));
501
+ const { APPBOUNDRY_PACKAGE, MINIMUM_APPBOUNDRY, appboundryProblems, installHint, probeAppBoundry } = await import("../appboundry/runtime.js");
502
+ line(c.dim(`Serve it with AppBoundry ${MINIMUM_APPBOUNDRY} or later: npx ${APPBOUNDRY_PACKAGE}@^${MINIMUM_APPBOUNDRY} run ${relativeArtifact}`));
503
+ // An AppBoundry installed in this project must be able to run what was just built.
504
+ const installed = join(projectDir, "node_modules", ...APPBOUNDRY_PACKAGE.split("/"), "dist", "bin.js");
505
+ if (existsSync(installed)) {
506
+ let problems;
507
+ let version = "";
508
+ try {
509
+ const report = probeAppBoundry(installed);
510
+ version = report.version;
511
+ problems = appboundryProblems(report, m);
512
+ }
513
+ catch (error) {
514
+ problems = [error.message];
515
+ }
516
+ if (problems.length) {
517
+ line(`${symbols.fail} The ${APPBOUNDRY_PACKAGE}${version ? ` ${version}` : ""} installed in this project cannot run it: ${problems.join("; ")}`);
518
+ line(c.dim(` ${installHint()}`));
519
+ return 1;
520
+ }
521
+ line(`${symbols.ok} ${APPBOUNDRY_PACKAGE} ${version} installed in this project runs it`);
522
+ }
444
523
  return 0;
445
524
  }
446
525
  // Not an error: a FeltKit server runs all of it. Said now so a team learns before relying on the artifact target.
@@ -459,6 +538,7 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
459
538
  const server = await startProduction({
460
539
  projectDir,
461
540
  environment: envName,
541
+ ...(flags.migrate === false || process.env.FELTKIT_MIGRATE === "manual" ? { migrate: "manual" } : {}),
462
542
  ...(flags.port ? { port: Number(flags.port) } : {}),
463
543
  ...(flags.host ? { host: String(flags.host) } : {}),
464
544
  });
@@ -477,6 +557,34 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
477
557
  return 0;
478
558
  }
479
559
  const tsx = import.meta.resolve("tsx");
560
+ if (json) {
561
+ // One JSON report: each test with its outcome and, for a failure, what it expected and got.
562
+ const reporter = fileURLToPath(new URL(`./test-reporter${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
563
+ const { code, stdout, stderr } = await new Promise((done) => {
564
+ const child = spawn(process.execPath, ["--import", tsx, "--test", "--test-concurrency=1", `--test-reporter=${reporter}`, "--test-reporter-destination=stdout", ...files], {
565
+ cwd: projectDir,
566
+ stdio: ["ignore", "pipe", "pipe"],
567
+ env: { ...Object.fromEntries(Object.entries(process.env).filter(([k]) => k !== "NODE_TEST_CONTEXT")), FELTKIT_ENV: "test", FELTKIT_NO_REGISTRY: "1" },
568
+ });
569
+ let out = "";
570
+ let err = "";
571
+ child.stdout.on("data", (d) => (out += d));
572
+ child.stderr.on("data", (d) => (err += d));
573
+ child.on("exit", (status) => done({ code: status ?? 1, stdout: out, stderr: err }));
574
+ });
575
+ const tests = stdout.split("\n").filter((l) => l.startsWith("{")).map((l) => JSON.parse(l));
576
+ const report = {
577
+ ok: code === 0,
578
+ passed: tests.filter((t) => t.ok && !t.skipped).length,
579
+ failed: tests.filter((t) => !t.ok).length,
580
+ skipped: tests.filter((t) => t.skipped).length,
581
+ files: files.map((f) => relative(projectDir, resolve(projectDir, f))),
582
+ tests: tests.map((t) => ({ ...t, file: t.file ? relative(projectDir, t.file.startsWith("file:") ? fileURLToPath(t.file) : t.file) : null })),
583
+ ...(code !== 0 && !tests.some((t) => !t.ok) ? { error: stderr.slice(-4000) || `node --test exited with ${code}` } : {}),
584
+ };
585
+ line(JSON.stringify(report, null, 2));
586
+ return code;
587
+ }
480
588
  const code = await new Promise((done) => {
481
589
  const child = spawn(process.execPath, ["--import", tsx, "--test", "--test-concurrency=1", ...files], {
482
590
  cwd: projectDir,
@@ -488,6 +596,194 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
488
596
  });
489
597
  return code;
490
598
  }
599
+ case "migrate": {
600
+ if (flags.history) {
601
+ const { value, source } = await withEnvironment(projectDir, envName, (record, token) => adminRequest(record, token, "/schema"), async (runtime) => ({ history: await runtime.schemaHistory() }));
602
+ const history = value.history;
603
+ if (json)
604
+ line(JSON.stringify({ source, history }, null, 2));
605
+ else {
606
+ line(c.dim(`From ${source}`));
607
+ if (!history.length)
608
+ line(`${symbols.info} No schema changes recorded in ${envName}.`);
609
+ for (const h of history)
610
+ 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(", ")}` : ""}`);
611
+ }
612
+ return 0;
613
+ }
614
+ const { value: planned, source } = await withEnvironment(projectDir, envName, async (record, token) => (await adminRequest(record, token, "/schema")).plan, async (runtime) => runtime.schemaPlan());
615
+ const plan = planned;
616
+ if (!json) {
617
+ line(c.dim(`From ${source}`));
618
+ for (const text of describePlan(plan))
619
+ line(text);
620
+ }
621
+ if (plan.status === "current") {
622
+ if (json)
623
+ line(JSON.stringify({ source, plan, applied: null }, null, 2));
624
+ return 0;
625
+ }
626
+ if (plan.status === "unmanaged" || plan.status === "blocked") {
627
+ if (json)
628
+ line(JSON.stringify({ source, plan, applied: null }, null, 2));
629
+ else if (plan.status === "blocked")
630
+ line(`${symbols.fail} ${plan.reason}\n ${c.dim(blockedHint(plan))}`);
631
+ return 1;
632
+ }
633
+ if (flags["dry-run"]) {
634
+ if (json)
635
+ line(JSON.stringify({ source, plan, applied: null, dryRun: true }, null, 2));
636
+ else
637
+ line(c.dim("\nDry run: nothing was changed."));
638
+ return 0;
639
+ }
640
+ if (!flags.yes) {
641
+ if (!process.stdin.isTTY)
642
+ 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." });
643
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
644
+ const answer = (await rl.question(`Apply to ${envName}? [y/N] `)).trim().toLowerCase();
645
+ rl.close();
646
+ if (answer !== "y" && answer !== "yes") {
647
+ line(c.dim("Nothing was changed."));
648
+ return 1;
649
+ }
650
+ }
651
+ const by = `feltkit migrate (${defaultOwnerId()})`;
652
+ 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 }));
653
+ const applied = result;
654
+ if (json)
655
+ line(JSON.stringify({ source, plan, applied }, null, 2));
656
+ else if (applied)
657
+ 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.`);
658
+ else
659
+ line(`${symbols.info} Nothing to apply.`);
660
+ return 0;
661
+ }
662
+ case "backup": {
663
+ const action = positional[0];
664
+ const project = async () => loadProjectFor(projectDir, envName);
665
+ const environmentFor = async () => {
666
+ const env = envName === "production" ? productionEnv(projectDir) : artifactEnv(projectDir);
667
+ const loaded = await project();
668
+ return { app: loaded.app, environment: resolveEnvironment({ projectDir, appName: loaded.app.name, name: envName, env }) };
669
+ };
670
+ if (action === "create") {
671
+ const runtimeDir = join(projectDir, ".feltkit", envName);
672
+ const record = readRuntimeRecord(runtimeDir);
673
+ let lines;
674
+ let source;
675
+ if (record) {
676
+ if (envName === "production")
677
+ 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.`);
678
+ const token = readAdminToken(runtimeDir);
679
+ if (!token)
680
+ throw new FeltKitError("CONFIGURATION", `A ${envName} server is running (pid ${record.pid}) but its admin token is missing.`);
681
+ lines = (await adminRequest(record, token, "/backup", { method: "POST" })).lines;
682
+ source = `running server (pid ${record.pid}; calls paused while it read)`;
683
+ }
684
+ else {
685
+ const { app, environment } = await environmentFor();
686
+ lines = await backupEnvironment(environment, app);
687
+ source = "the stopped environment, directly";
688
+ }
689
+ const header = JSON.parse(lines[0]);
690
+ const out = resolve(typeof flags.out === "string" ? flags.out : join(projectDir, ".feltkit", "backups", envName, `${header.application.name}-${header.createdAt.replace(/[:.]/g, "-")}.ndjson`));
691
+ mkdirSync(dirname(out), { recursive: true });
692
+ if (existsSync(out))
693
+ throw new FeltKitError("CONFLICT", `${out} exists; a backup never overwrites a file.`);
694
+ writeFileSync(`${out}.partial`, `${lines.join("\n")}\n`);
695
+ verifyBackup(readFileSync(`${out}.partial`, "utf8"));
696
+ renameSync(`${out}.partial`, out);
697
+ if (json)
698
+ line(JSON.stringify({ path: out, source, header }, null, 2));
699
+ else
700
+ 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.`);
701
+ return 0;
702
+ }
703
+ if (action === "verify") {
704
+ const file = positional[1];
705
+ if (!file)
706
+ throw new FeltKitError("INVALID_ARGUMENT", "Usage: feltkit backup verify <file>");
707
+ const { header, records } = verifyBackup(readFileSync(resolve(file), "utf8"));
708
+ if (json)
709
+ line(JSON.stringify({ ok: true, header, records: records.length }, null, 2));
710
+ else
711
+ line(`${symbols.ok} ${file}: ${header.application.name} ${header.application.version} (${header.environment}, ${header.createdAt}); ${records.length} records; contract ${header.contract ? `${header.contract.name} v${header.contract.version} ${header.contract.hash.slice(0, 19)}…` : "none"}; FeltKit ${header.feltkit}, FeltDB ${header.feltdb}.`);
712
+ return 0;
713
+ }
714
+ if (action === "list") {
715
+ const dir = resolve(typeof flags.dir === "string" ? flags.dir : join(projectDir, ".feltkit", "backups"));
716
+ 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() : [];
717
+ const items = files.map((path) => {
718
+ try {
719
+ const { header, records } = verifyBackup(readFileSync(path, "utf8"));
720
+ 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: records.length };
721
+ }
722
+ catch (error) {
723
+ return { path, ok: false, error: error.message };
724
+ }
725
+ });
726
+ if (json)
727
+ line(JSON.stringify({ dir, items }, null, 2));
728
+ else if (!items.length)
729
+ line(`${symbols.info} No backups in ${relative(process.cwd(), dir) || dir}.`);
730
+ else
731
+ for (const i of items)
732
+ 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}`);
733
+ return items.every((i) => i.ok) ? 0 : 1;
734
+ }
735
+ if (action === "restore") {
736
+ const file = positional[1];
737
+ if (!file)
738
+ throw new FeltKitError("INVALID_ARGUMENT", "Usage: feltkit backup restore <file> --env <env>");
739
+ if (readRuntimeRecord(join(projectDir, ".feltkit", envName)))
740
+ throw new FeltKitError("CONFLICT", `A ${envName} server is running; a restore writes only into a new, empty environment. Nothing was written.`);
741
+ const { app, environment } = await environmentFor();
742
+ const { header, records } = await restoreEnvironment(readFileSync(resolve(file), "utf8"), environment, app);
743
+ if (json)
744
+ line(JSON.stringify({ restored: true, environment: envName, header, records }, null, 2));
745
+ else
746
+ 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.`);
747
+ return 0;
748
+ }
749
+ line(COMMAND_HELP.backup);
750
+ return 1;
751
+ }
752
+ case "outbox": {
753
+ const action = positional[0] ?? "list";
754
+ if (action === "list") {
755
+ const state = typeof flags.state === "string" ? flags.state : undefined;
756
+ if (state && !["pending", "performing", "done", "failed"].includes(state))
757
+ throw new FeltKitError("INVALID_ARGUMENT", "--state is pending, performing, done or failed.");
758
+ 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 } : {}));
759
+ if (json)
760
+ line(JSON.stringify({ source, items: value }, null, 2));
761
+ else {
762
+ line(c.dim(`From ${source}`));
763
+ if (!value.length)
764
+ line(`${symbols.info} No after-commit effects${state ? ` in state ${state}` : ""} in ${envName}.`);
765
+ for (const r of value) {
766
+ const effect = r.effect.service === "notifications" ? `notifications.send ${r.effect.input.type}` : `${r.effect.service}.${r.effect.method} ${r.effect.type}`;
767
+ 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}` : ""}`);
768
+ }
769
+ }
770
+ return 0;
771
+ }
772
+ if (action === "retry") {
773
+ const id = positional[1];
774
+ if (!id)
775
+ throw new FeltKitError("INVALID_ARGUMENT", "Usage: feltkit outbox retry <id> (see `feltkit outbox list --state failed`)");
776
+ const by = `feltkit outbox retry (${defaultOwnerId()})`;
777
+ 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));
778
+ if (json)
779
+ line(JSON.stringify(value, null, 2));
780
+ else
781
+ 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}` : ""}.`);
782
+ return value.state === "failed" ? 1 : 0;
783
+ }
784
+ line(COMMAND_HELP.outbox);
785
+ return 1;
786
+ }
491
787
  case "inspect": {
492
788
  const { value, source } = await withEnvironment(projectDir, envName, (record, token) => adminRequest(record, token, "/overview"), async (runtime) => overviewPayload(runtime));
493
789
  if (json)
@@ -511,6 +807,13 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
511
807
  throw new FeltKitError("INVALID_ARGUMENT", `Answer 1-${choices.length}.`);
512
808
  }
513
809
  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) } : {}) });
810
+ if (json) {
811
+ // What a caller (the platform's change.apply) can rely on: deploy() returns only after the
812
+ // production build booted against isolated state and answered its health and capability checks.
813
+ const bundle = join(result.dir, BUILD_DIR, "functions.mjs");
814
+ 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));
815
+ return 0;
816
+ }
514
817
  line(`${symbols.ok} Built and verified: the production build booted against a temporary state directory and answered health and capability checks.`);
515
818
  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
819
  // Paths relative to where the command ran, one command per line, so each can be pasted.
@@ -999,6 +1302,141 @@ export async function main(argv = process.argv.slice(2), deps = {}) {
999
1302
  }
1000
1303
  return 0;
1001
1304
  }
1305
+ case "op": {
1306
+ // FeltKit's development and operations capabilities (docs/AGENT-OPERATIONS.md), as the
1307
+ // workspace owner: through the running `platform serve` when there is one, else in process.
1308
+ const root = resolve(String(flags.root ?? process.cwd()));
1309
+ const { OPERATIONS } = await import("../platform/operations.js");
1310
+ const name = positional[0];
1311
+ if (!name || name === "list") {
1312
+ 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 }));
1313
+ if (json)
1314
+ line(JSON.stringify({ application: "dev.feltkit.platform", operations: catalog }, null, 2));
1315
+ else
1316
+ for (const op of catalog)
1317
+ line(` ${c.bold(op.name.padEnd(16))} ${op.effect.padEnd(12)} ${c.dim(op.permission.padEnd(26))} ${op.description}`);
1318
+ return 0;
1319
+ }
1320
+ let input = {};
1321
+ try {
1322
+ input = flags.input ? JSON.parse(String(flags.input)) : {};
1323
+ }
1324
+ catch {
1325
+ throw new FeltKitError("INVALID_ARGUMENT", "--input must be JSON, e.g. --input '{\"project\":\"my-app\"}'");
1326
+ }
1327
+ if (flags.project && input && typeof input === "object")
1328
+ input.project = String(flags.project);
1329
+ const { runningPlatform } = await import("../platform/server.js");
1330
+ const running = runningPlatform(root);
1331
+ let result;
1332
+ if (running) {
1333
+ 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 }) });
1334
+ const body = (await response.json());
1335
+ const decisionId = body.authorizationDecision?.decisionId ?? body.error?.details?.decisionId;
1336
+ result = { ok: body.ok, ...(body.ok ? { output: body.output } : { error: body.error }), ...(decisionId ? { decisionId } : {}) };
1337
+ }
1338
+ else {
1339
+ const { Platform, localOwner } = await import("../platform/platform.js");
1340
+ const platform = Platform.open(root);
1341
+ try {
1342
+ result = await platform.invoke(name, input, { principal: localOwner(), transport: "cli" });
1343
+ }
1344
+ finally {
1345
+ await platform.close();
1346
+ }
1347
+ }
1348
+ if (json)
1349
+ line(JSON.stringify(result, null, 2));
1350
+ else if (result.ok)
1351
+ line(JSON.stringify(result.output, null, 2));
1352
+ else
1353
+ line(`${symbols.fail} ${result.error?.code}: ${result.error?.message}${result.decisionId ? c.dim(` (decision ${result.decisionId})`) : ""}`);
1354
+ return result.ok ? 0 : 1;
1355
+ }
1356
+ case "platform": {
1357
+ const root = resolve(String(flags.root ?? process.cwd()));
1358
+ const action = positional[0];
1359
+ const { runningPlatform, servePlatform } = await import("../platform/server.js");
1360
+ if (action === "serve") {
1361
+ if (runningPlatform(root))
1362
+ throw new FeltKitError("INVALID_ARGUMENT", `A platform server is already running for ${root} (.feltkit-platform/server.json).`);
1363
+ const { Platform } = await import("../platform/platform.js");
1364
+ const platform = Platform.open(root);
1365
+ const served = await servePlatform(platform, { ...(flags.port ? { port: Number(flags.port) } : {}), ...(flags.host ? { host: String(flags.host) } : {}) });
1366
+ line(`${symbols.ok} FeltKit platform for ${c.bold(root)}`);
1367
+ line(` AppPort ${served.url}/appport ${c.dim(`(manifest ${served.url}/appport/manifest)`)}`);
1368
+ line(` MCP ${served.url}/mcp`);
1369
+ line(c.dim("Every request needs a platform session: `feltkit platform session create --id <agent> --profile inspect|develop`."));
1370
+ await waitForShutdown(async () => {
1371
+ await served.close();
1372
+ await platform.close();
1373
+ });
1374
+ return 0;
1375
+ }
1376
+ if (action === "session") {
1377
+ const sub = positional[1];
1378
+ const running = runningPlatform(root);
1379
+ const remote = async (path, init = {}) => {
1380
+ const response = await fetch(`${running.url}${path}`, { ...init, headers: { "content-type": "application/json", authorization: `Bearer ${running.token}` } });
1381
+ const body = (await response.json());
1382
+ if (!body.ok)
1383
+ throw new FeltKitError("INVALID_ARGUMENT", body.error?.message ?? `platform server answered ${response.status}`);
1384
+ return body;
1385
+ };
1386
+ const local = async (work) => {
1387
+ const { Platform } = await import("../platform/platform.js");
1388
+ const platform = Platform.open(root);
1389
+ try {
1390
+ return await work(platform);
1391
+ }
1392
+ finally {
1393
+ await platform.close();
1394
+ }
1395
+ };
1396
+ if (sub === "create") {
1397
+ if (!flags.id || !flags.profile)
1398
+ throw new FeltKitError("INVALID_ARGUMENT", "Usage: feltkit platform session create --id <id> --profile inspect|develop|deploy:<project>/<environment>|owner [--type agent]");
1399
+ 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) } : {}) };
1400
+ const issued = running
1401
+ ? await remote("/platform/sessions", { method: "POST", body: JSON.stringify(request) })
1402
+ : await local(async (platform) => {
1403
+ const session = await platform.issue(request);
1404
+ return { token: session.id, ...(session.expiresAt ? { expiresAt: session.expiresAt } : {}) };
1405
+ });
1406
+ if (json)
1407
+ line(JSON.stringify({ token: issued.token, principal: { id: request.id, type: request.type, profile: request.profile }, ...(issued.expiresAt ? { expiresAt: issued.expiresAt } : {}) }, null, 2));
1408
+ else {
1409
+ line(`${symbols.ok} Platform session for ${c.bold(request.id)} (${request.type}, profile ${request.profile})`);
1410
+ line(`\n ${issued.token}\n`);
1411
+ line(c.dim("Shown once. Use it as `Authorization: Bearer <token>` against the platform's /appport and /mcp. Revoke with `feltkit platform session revoke`."));
1412
+ }
1413
+ return 0;
1414
+ }
1415
+ if (sub === "list") {
1416
+ const sessions = running ? (await remote("/platform/sessions")).sessions : await local((platform) => platform.sessions.list());
1417
+ if (json)
1418
+ line(JSON.stringify(sessions, null, 2));
1419
+ else if (!sessions.length)
1420
+ line(`${symbols.info} No active platform sessions.`);
1421
+ else
1422
+ for (const s of sessions)
1423
+ 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")}`);
1424
+ return 0;
1425
+ }
1426
+ if (sub === "revoke") {
1427
+ const ref = positional[2] ?? (flags.principal ? `principal:${flags.principal}` : undefined);
1428
+ if (!ref)
1429
+ throw new FeltKitError("INVALID_ARGUMENT", "Usage: feltkit platform session revoke <ref> | --principal <id>");
1430
+ const revoked = running
1431
+ ? (await remote(`/platform/sessions/${encodeURIComponent(ref)}`, { method: "DELETE" })).revoked
1432
+ : await local((platform) => (ref.startsWith("principal:") ? platform.sessions.revokePrincipal(ref.slice("principal:".length)) : platform.sessions.revoke(ref)));
1433
+ line(revoked ? `${symbols.ok} Revoked ${revoked} session${revoked === 1 ? "" : "s"}` : `${symbols.fail} No session matches ${ref}`);
1434
+ return revoked ? 0 : 1;
1435
+ }
1436
+ }
1437
+ line(COMMAND_HELP.platform);
1438
+ return 1;
1439
+ }
1002
1440
  case "skills": {
1003
1441
  const action = positional[0];
1004
1442
  const target = skillsTarget({ projectDir, user: flags.user === true, ...(flags.dir ? { dir: String(flags.dir) } : {}) });