@north-light/cli 0.3.755 → 0.3.757

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 (138) hide show
  1. package/dist/api/client.d.ts +1 -2
  2. package/dist/api/client.js +3 -3
  3. package/dist/api/contract.d.ts +1 -1
  4. package/dist/api/contract.js +1 -1
  5. package/dist/api/dto/health.d.ts +0 -54
  6. package/dist/api/routes.d.ts +0 -1
  7. package/dist/api/routes.js +1 -1
  8. package/dist/build-root.d.ts +0 -3
  9. package/dist/build-root.js +1 -1
  10. package/dist/builtin-memory/internal/storage-tiers.md +3 -3
  11. package/dist/cli.js +8 -9
  12. package/dist/clients/attach/viewer.js +474 -474
  13. package/dist/commands/profile/new.js +1 -1
  14. package/dist/commands/profile/project.js +1 -1
  15. package/dist/commands/sys/branch.js +1 -1
  16. package/dist/commands/sys/daemon.js +1 -1
  17. package/dist/commands/sys.js +1 -1
  18. package/dist/core/bootstrap.js +1 -1
  19. package/dist/core/canvas/boot.d.ts +0 -25
  20. package/dist/core/canvas/boot.js +1 -1
  21. package/dist/core/canvas/executions.d.ts +0 -3
  22. package/dist/core/canvas/executions.js +1 -1
  23. package/dist/core/canvas/pid.d.ts +0 -10
  24. package/dist/core/canvas/pid.js +5 -5
  25. package/dist/core/directory/join.js +1 -1
  26. package/dist/core/grants/mirror.d.ts +0 -5
  27. package/dist/core/grants/mirror.js +6 -6
  28. package/dist/core/grants/sync.js +1 -1
  29. package/dist/core/human/page-schema.d.ts +1 -1
  30. package/dist/core/io.js +4 -4
  31. package/dist/core/layout.d.ts +0 -2
  32. package/dist/core/layout.js +2 -2
  33. package/dist/core/profiles/manifest.js +1 -1
  34. package/dist/core/profiles/project-dir.d.ts +3 -0
  35. package/dist/core/profiles/project-dir.js +1 -0
  36. package/dist/core/scoped-state/db.js +2 -2
  37. package/dist/daemon/api/handlers/daemon.js +1 -1
  38. package/dist/daemon/api/handlers/profiles.js +1 -1
  39. package/dist/daemon/api/map.d.ts +1 -6
  40. package/dist/daemon/api/map.js +2 -2
  41. package/dist/daemon/api/operations.js +1 -1
  42. package/dist/daemon/api/server.js +1 -1
  43. package/dist/daemon/control.d.ts +0 -8
  44. package/dist/daemon/crtrd.js +18 -20
  45. package/dist/daemon/manage.js +3 -3
  46. package/package.json +3 -3
  47. package/packages/crouter-api/dist/api/client.js +0 -3
  48. package/packages/crouter-api/dist/api/contract.js +1 -1
  49. package/packages/crouter-api/dist/api/routes.js +0 -1
  50. package/packages/crouter-api/dist/build-root.js +0 -9
  51. package/packages/crouter-api/dist/commands/profile/new.js +2 -2
  52. package/packages/crouter-api/dist/commands/profile/project.js +2 -1
  53. package/packages/crouter-api/dist/commands/sys/branch.js +1 -1
  54. package/packages/crouter-api/dist/commands/sys/daemon.js +1 -1
  55. package/packages/crouter-api/dist/commands/sys.js +1 -2
  56. package/packages/crouter-api/dist/core/canvas/executions.js +1 -17
  57. package/packages/crouter-api/dist/core/canvas/pid.js +0 -16
  58. package/packages/crouter-api/dist/core/directory/join.js +18 -1
  59. package/packages/crouter-api/dist/core/grants/mirror.js +0 -7
  60. package/packages/crouter-api/dist/core/grants/sync.js +2 -2
  61. package/packages/crouter-api/dist/core/io.js +0 -5
  62. package/packages/crouter-api/dist/core/layout.js +2 -19
  63. package/packages/crouter-api/dist/core/profiles/manifest.js +12 -18
  64. package/packages/crouter-api/dist/core/profiles/project-dir.js +20 -0
  65. package/packages/crouter-api/dist/daemon/api/map.js +0 -16
  66. package/packages/crouter-api/dist/daemon/api/operations.js +0 -1
  67. package/packages/crouter-api/dist/daemon/manage.js +1 -1
  68. package/packages/crouter-api/package.json +1 -1
  69. package/packages/crouter-identity/package.json +1 -1
  70. package/packages/crouter-plugin/package.json +3 -3
  71. package/runtime.lock.json +14 -14
  72. package/scripts/install-runtime.mjs +1 -30
  73. package/dist/commands/sys/migrate.d.ts +0 -1
  74. package/dist/commands/sys/migrate.js +0 -1
  75. package/dist/core/canvas/import-sqlite.d.ts +0 -46
  76. package/dist/core/canvas/import-sqlite.js +0 -19
  77. package/dist/core/canvas/migrations.d.ts +0 -16
  78. package/dist/core/canvas/migrations.js +0 -1073
  79. package/dist/core/feed/inbox-migrate.d.ts +0 -11
  80. package/dist/core/feed/inbox-migrate.js +0 -3
  81. package/dist/core/graph/bodies-boot-copy.d.ts +0 -28
  82. package/dist/core/graph/bodies-boot-copy.js +0 -1
  83. package/dist/core/layout-migrate/index.d.ts +0 -38
  84. package/dist/core/layout-migrate/index.js +0 -4
  85. package/dist/core/layout-migrate/loose-keys.d.ts +0 -2
  86. package/dist/core/layout-migrate/loose-keys.js +0 -1
  87. package/dist/core/layout-migrate/paths.d.ts +0 -30
  88. package/dist/core/layout-migrate/paths.js +0 -1
  89. package/dist/core/layout-migrate/stored-paths.d.ts +0 -9
  90. package/dist/core/layout-migrate/stored-paths.js +0 -11
  91. package/dist/core/layout-migrate/stores.d.ts +0 -30
  92. package/dist/core/layout-migrate/stores.js +0 -3
  93. package/dist/core/scoped-state/migrate.d.ts +0 -15
  94. package/dist/core/scoped-state/migrate.js +0 -3
  95. package/dist/daemon/boot-migrations.d.ts +0 -14
  96. package/dist/daemon/boot-migrations.js +0 -1
  97. package/dist/migrations/004-canvas-documents/apply.d.ts +0 -8
  98. package/dist/migrations/004-canvas-documents/apply.js +0 -1
  99. package/dist/migrations/004-canvas-documents/index.d.ts +0 -16
  100. package/dist/migrations/004-canvas-documents/index.js +0 -2
  101. package/dist/migrations/004-canvas-documents/legacy/discover.d.ts +0 -16
  102. package/dist/migrations/004-canvas-documents/legacy/discover.js +0 -1
  103. package/dist/migrations/004-canvas-documents/legacy/history.d.ts +0 -5
  104. package/dist/migrations/004-canvas-documents/legacy/history.js +0 -2
  105. package/dist/migrations/004-canvas-documents/legacy/nested.d.ts +0 -7
  106. package/dist/migrations/004-canvas-documents/legacy/nested.js +0 -1
  107. package/dist/migrations/004-canvas-documents/legacy/parse.d.ts +0 -14
  108. package/dist/migrations/004-canvas-documents/legacy/parse.js +0 -1
  109. package/dist/migrations/004-canvas-documents/legacy/types.d.ts +0 -91
  110. package/dist/migrations/004-canvas-documents/legacy/types.js +0 -0
  111. package/dist/migrations/004-canvas-documents/legacy-edges.d.ts +0 -6
  112. package/dist/migrations/004-canvas-documents/legacy-edges.js +0 -18
  113. package/dist/migrations/004-canvas-documents/plan.d.ts +0 -102
  114. package/dist/migrations/004-canvas-documents/plan.js +0 -3
  115. package/dist/migrations/004-canvas-documents/pointers.d.ts +0 -23
  116. package/dist/migrations/004-canvas-documents/pointers.js +0 -4
  117. package/dist/migrations/activation.d.ts +0 -17
  118. package/dist/migrations/activation.js +0 -2
  119. package/packages/crouter-api/dist/commands/sys/migrate.js +0 -79
  120. package/packages/crouter-api/dist/core/layout-migrate/index.js +0 -523
  121. package/packages/crouter-api/dist/core/layout-migrate/paths.js +0 -118
  122. package/packages/crouter-api/dist/core/layout-migrate/stored-paths.js +0 -424
  123. package/packages/crouter-api/dist/core/layout-migrate/stores.js +0 -543
  124. package/packages/crouter-api/dist/core/locked-file.js +0 -121
  125. package/packages/crouter-api/dist/core/scoped-state/db.js +0 -271
  126. package/packages/crouter-api/dist/core/scoped-state/legacy-profiles.js +0 -65
  127. package/packages/crouter-api/dist/core/scoped-state/migrate.js +0 -332
  128. package/packages/crouter-api/dist/core/scoped-state/schema.js +0 -52
  129. package/packages/crouter-api/dist/migrations/004-canvas-documents/apply.js +0 -113
  130. package/packages/crouter-api/dist/migrations/004-canvas-documents/index.js +0 -89
  131. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/discover.js +0 -251
  132. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/history.js +0 -37
  133. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/nested.js +0 -37
  134. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/parse.js +0 -24
  135. package/packages/crouter-api/dist/migrations/004-canvas-documents/legacy/types.js +0 -3
  136. package/packages/crouter-api/dist/migrations/004-canvas-documents/plan.js +0 -410
  137. package/packages/crouter-api/dist/migrations/004-canvas-documents/pointers.js +0 -95
  138. package/packages/crouter-api/dist/migrations/activation.js +0 -46
@@ -102,26 +102,9 @@ export function assertSupportedLayoutMarker(path) {
102
102
  throw new Error(`unsupported runtime layout version: ${path} holds ${describeLayoutMarker(bytes)}; expected "${LAYOUT_VERSION}"`);
103
103
  }
104
104
  }
105
- /** A missing version on an occupied volume is never initialized by daemon startup. */
106
- export function layoutNeedsMigration() {
107
- if (process.env['CRTR_LAYOUT_REFUSE'] === '1')
108
- return true;
109
- if (existsSync(layoutVersionFile())) {
110
- assertSupportedLayoutMarker(layoutVersionFile());
111
- return false;
112
- }
113
- const root = layoutRoot();
114
- const volume = process.platform === 'linux' && root === '/' && existsSync('/volume') ? '/volume' : root;
115
- if (existsSync(join(volume, 'canvas')) || existsSync(join(volume, 'canvas.db')))
116
- return true;
117
- // A moved canvas.db without a layout version is an unfinished offline
118
- // migration. Node records move before the DB, so the old or moved DB always
119
- // accompanies them; entrypoint-created directories are a fresh volume.
120
- return existsSync(join(runtimeRoot(), 'canvas.db'));
121
- }
122
105
  export function initializeEmptyLayout() {
123
- if (layoutNeedsMigration())
124
- throw new Error('layout_migration_required');
106
+ if (existsSync(layoutVersionFile()))
107
+ assertSupportedLayoutMarker(layoutVersionFile());
125
108
  for (const dir of [runtimeRoot(), userRoot(), appsRoot(), secretsDir()]) {
126
109
  // mkdir returns the first directory it had to create; every entry from there down to
127
110
  // `dir` is new, and so is the entry for the first one in its (existing) parent.
@@ -1,7 +1,8 @@
1
1
  // Profile definitions live in scoped state; memory and environment have separate roots.
2
2
  import { randomUUID } from 'node:crypto';
3
- import { existsSync, realpathSync, rmSync, statSync } from 'node:fs';
4
- import { resolve as resolvePath } from 'node:path';
3
+ import { realpathSync, rmSync } from 'node:fs';
4
+ import { isAbsolute, resolve as resolvePath } from 'node:path';
5
+ import { resolveExistingProjectDir } from './project-dir.js';
5
6
  import { SCHEMA_VERSION } from '../../types.js';
6
7
  import { profileSpace } from '../layout.js';
7
8
  import { PROFILE_PROJECT_MEMORY_VALUES } from '../../api/dto/profiles.js';
@@ -165,20 +166,13 @@ export function matchProfileOperand(all, operand, key) {
165
166
  }
166
167
  // Project dirs — resolved to absolute real paths, must exist + be a directory
167
168
  // on add/create, deduped by real path, stored in manifest order.
168
- function resolveExistingProjectDir(dir) {
169
- const abs = resolvePath(dir);
170
- if (!existsSync(abs) || !statSync(abs).isDirectory()) {
171
- throw usage(`project directory does not exist or is not a directory: ${dir}`, {
172
- received: dir,
173
- next: 'Pass an existing directory path.',
174
- });
175
- }
176
- try {
177
- return realpathSync(abs);
178
- }
179
- catch {
180
- return abs;
181
- }
169
+ /** A cloud role cannot see the caller's disk: the caller's CLI already resolved the path on its own machine, so it is stored as sent. */
170
+ function storedProjectDir(dir) {
171
+ if (!isCloudRole())
172
+ return resolveExistingProjectDir(dir);
173
+ if (!isAbsolute(dir))
174
+ throw usage(`project directory must be an absolute path: ${dir}`, { received: dir });
175
+ return dir;
182
176
  }
183
177
  /** First-wins by resolved path; by repo only among entries with no path. A folder entry for a repo that has a repo-only entry merges into it
184
178
  * (one entry, both fields, the repo-only entry's position). */
@@ -342,7 +336,7 @@ export async function createProfile(name, projects = [], opts = {}) {
342
336
  if (opts.metadata !== undefined)
343
337
  assertProfileMetadata(opts.metadata);
344
338
  assertProfileProjects(projects);
345
- const resolvedProjects = dedupeProjects(projects.map((p) => ({ ...(p.repo === undefined ? {} : { repo: p.repo }), ...(p.path === undefined ? {} : { path: resolveExistingProjectDir(p.path) }) })));
339
+ const resolvedProjects = dedupeProjects(projects.map((p) => ({ ...(p.repo === undefined ? {} : { repo: p.repo }), ...(p.path === undefined ? {} : { path: storedProjectDir(p.path) }) })));
346
340
  const profileId = generateProfileId(trimmed);
347
341
  const manifest = {
348
342
  schema_version: SCHEMA_VERSION,
@@ -505,7 +499,7 @@ export async function renameProfile(profileId, name) {
505
499
  * a folder no repo identifies keeps `path` only. A listed entry with that path but no repo gains the repo in place. */
506
500
  export async function addProfileProject(profileId, dir, repo) {
507
501
  assertProfileProjects([{ path: dir, ...(repo === undefined ? {} : { repo }) }]);
508
- const resolved = resolveExistingProjectDir(dir);
502
+ const resolved = storedProjectDir(dir);
509
503
  return await mutateManifest(profileId, (m) => ({
510
504
  ...m,
511
505
  projects: dedupeProjects(m.projects.some((p) => p.path === resolved)
@@ -0,0 +1,20 @@
1
+ import { existsSync, realpathSync, statSync } from 'node:fs';
2
+ import { resolve as resolvePath } from 'node:path';
3
+ import { usage } from '../errors.js';
4
+ /** A project directory as an absolute real path; it must exist and be a directory on THIS machine's disk.
5
+ * The CLI runs this on the caller's machine before sending a path to a canvas that may live in the cloud. */
6
+ export function resolveExistingProjectDir(dir) {
7
+ const abs = resolvePath(dir);
8
+ if (!existsSync(abs) || !statSync(abs).isDirectory()) {
9
+ throw usage(`project directory does not exist or is not a directory: ${dir}`, {
10
+ received: dir,
11
+ next: 'Pass an existing directory path.',
12
+ });
13
+ }
14
+ try {
15
+ return realpathSync(abs);
16
+ }
17
+ catch {
18
+ return abs;
19
+ }
20
+ }
@@ -27,22 +27,6 @@ import { WorktreeError } from '../../core/worktree.js';
27
27
  import { ApiError } from '../../api/errors.js';
28
28
  import { RunError } from '../../core/runs/operations.js';
29
29
  import { ExitCode } from '../../types.js';
30
- export function toMigrateStateDTO(result, options) {
31
- const { report } = result;
32
- return {
33
- stores: report.stores.map((s) => ({ root: s.root, owner: { ...s.owner }, docs: s.docs, ...(s.skipped === undefined ? {} : { skipped: s.skipped }) })),
34
- counts: report.counts,
35
- rewrites: report.rewrites,
36
- dropped_fields: report.droppedFields,
37
- skipped: report.skipped,
38
- resolutions: report.resolutions.map((r) => ({ kind: r.kind, message: r.message, paths: r.paths })),
39
- blockers: result.blockers.map((b) => ({ kind: b.kind, message: b.message, paths: b.paths })),
40
- dryRun: result.dryRun,
41
- pending: result.pending,
42
- resumed: options.resumed,
43
- ...(options.resumeError === undefined ? {} : { resume_error: options.resumeError }),
44
- };
45
- }
46
30
  // Node projections
47
31
  /** Read the optional machine result without letting a missing or malformed sidecar obscure the durable outcome row. */
48
32
  async function readStructuredResult(nodeId) {
@@ -235,7 +235,6 @@ export const OPERATIONS = [
235
235
  { name: 'canvas.get.131', method: 'GET', path: '/v1/canvas/graph', classes: ['person', 'broker'], resource: 'canvas-read' },
236
236
  { name: 'canvas.post.132', method: 'POST', path: '/v1/canvas/prune', classes: ['person', 'broker'], resource: 'none' },
237
237
  { name: 'daemon.post.133', method: 'POST', path: '/v1/daemon/restart', classes: ['person', 'broker'], resource: 'daemon-control' },
238
- { name: 'daemon.post.134', method: 'POST', path: '/v1/daemon/migrate', classes: ['person', 'broker'], resource: 'daemon-control' },
239
238
  { name: 'daemon.drain.start', method: 'POST', path: '/v1/daemon/drain', classes: ['person'], resource: 'daemon-control' },
240
239
  { name: 'daemon.drain.end', method: 'DELETE', path: '/v1/daemon/drain', classes: ['person'], resource: 'daemon-control' },
241
240
  { name: 'daemon.post.135', method: 'POST', path: '/v1/daemon/admit', classes: ['person', 'broker'], resource: 'daemon-control' },
@@ -63,7 +63,7 @@ export const DAEMON_ENV_STRIP_KEYS = [
63
63
  const DAEMON_CRTR_ENV_NAMES = new Set([
64
64
  'CRTR_HOME', 'CRTR_RUNTIME_HOME', 'CRTR_PIDFILE', 'CRTR_RUNTIME', 'CRTR_INSTALL_ID',
65
65
  'CRTR_LOG', 'CRTR_DEBUG', 'CRTR_DEBUG_PID_LIVENESS', 'CRTR_TIMING', 'CRTR_TIMING_PROC',
66
- 'CRTR_NO_DAEMON_AUTOSTART', 'CRTR_NO_AUTO_UPDATE', 'CRTR_NO_AUTO_INIT', 'CRTR_NO_EXPORTS', 'CRTR_LAYOUT_REFUSE',
66
+ 'CRTR_NO_DAEMON_AUTOSTART', 'CRTR_NO_AUTO_UPDATE', 'CRTR_NO_AUTO_INIT', 'CRTR_NO_EXPORTS',
67
67
  'CRTR_POSTGRES_HOME', 'CRTR_DATABASE_URL', 'CRTR_DATABASE_SCHEMA', 'CRTR_DATABASE_POOL_MAX', 'CRTR_SCHEMA_DATABASE_URL',
68
68
  'CRTR_DOCUMENT_PORT', 'CRTR_LAUNCHER_SOCKET', 'CRTR_API_ADDRESS', 'CRTR_DIRECTORY_URL', 'CRTR_PUBLIC_API_URL',
69
69
  'CRTR_CANVAS_URL', 'CRTR_CANVAS_CLIENT_ID', 'CRTR_CANVAS_JWK_FILE', 'CRTR_SECRETS_KEY', 'CRTR_IMPORT_SERVICE_TOKEN',
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/api",
3
- "version": "0.3.755",
3
+ "version": "0.3.757",
4
4
  "description": "Typed crtrd /v1 API contract — DTOs, route builders, the error contract, the CrtrClient, and the command-plugin manifest format. Zero runtime dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/api/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/identity",
3
- "version": "0.3.755",
3
+ "version": "0.3.757",
4
4
  "description": "Northlight access-token verification and scope rules",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@north-light/plugin",
3
- "version": "0.3.755",
3
+ "version": "0.3.757",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -27,8 +27,8 @@
27
27
  "postpack": "node ../../scripts/pack-minify.mjs postpack packages/crouter-plugin"
28
28
  },
29
29
  "dependencies": {
30
- "@north-light/api": "0.3.755",
31
- "@north-light/identity": "0.3.755"
30
+ "@north-light/api": "0.3.757",
31
+ "@north-light/identity": "0.3.757"
32
32
  },
33
33
  "license": "UNLICENSED",
34
34
  "publishConfig": {
package/runtime.lock.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@north-light/cli",
3
- "version": "0.3.755",
3
+ "version": "0.3.757",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@north-light/cli",
9
- "version": "0.3.755",
9
+ "version": "0.3.757",
10
10
  "hasInstallScript": true,
11
11
  "license": "UNLICENSED",
12
12
  "workspaces": [
@@ -28,8 +28,8 @@
28
28
  "@milkdown/preset-gfm": "^7.22.3",
29
29
  "@milkdown/prose": "^7.22.3",
30
30
  "@milkdown/utils": "^7.22.3",
31
- "@north-light/identity": "0.3.755",
32
- "@north-light/plugin": "0.3.755",
31
+ "@north-light/identity": "0.3.757",
32
+ "@north-light/plugin": "0.3.757",
33
33
  "cron-parser": "^5.6.0",
34
34
  "esbuild": "0.28.2",
35
35
  "jose": "^6.2.12",
@@ -11902,17 +11902,17 @@
11902
11902
  },
11903
11903
  "packages/crouter-api": {
11904
11904
  "name": "@north-light/api",
11905
- "version": "0.3.755",
11905
+ "version": "0.3.757",
11906
11906
  "license": "UNLICENSED"
11907
11907
  },
11908
11908
  "packages/crouter-env-docker": {
11909
11909
  "name": "@north-light/env-docker",
11910
- "version": "0.3.755",
11910
+ "version": "0.3.757",
11911
11911
  "license": "UNLICENSED"
11912
11912
  },
11913
11913
  "packages/crouter-identity": {
11914
11914
  "name": "@north-light/identity",
11915
- "version": "0.3.755",
11915
+ "version": "0.3.757",
11916
11916
  "license": "UNLICENSED",
11917
11917
  "dependencies": {
11918
11918
  "jose": "^6.2.1"
@@ -11920,21 +11920,21 @@
11920
11920
  },
11921
11921
  "packages/crouter-plugin": {
11922
11922
  "name": "@north-light/plugin",
11923
- "version": "0.3.755",
11923
+ "version": "0.3.757",
11924
11924
  "license": "UNLICENSED",
11925
11925
  "dependencies": {
11926
- "@north-light/api": "0.3.755",
11927
- "@north-light/identity": "0.3.755"
11926
+ "@north-light/api": "0.3.757",
11927
+ "@north-light/identity": "0.3.757"
11928
11928
  }
11929
11929
  },
11930
11930
  "packages/crouter-sdk": {
11931
11931
  "name": "@north-light/sdk",
11932
- "version": "0.3.755",
11932
+ "version": "0.3.757",
11933
11933
  "license": "UNLICENSED",
11934
11934
  "dependencies": {
11935
- "@north-light/api": "0.3.755",
11936
- "@north-light/identity": "0.3.755",
11937
- "@north-light/plugin": "0.3.755",
11935
+ "@north-light/api": "0.3.757",
11936
+ "@north-light/identity": "0.3.757",
11937
+ "@north-light/plugin": "0.3.757",
11938
11938
  "jose": "^6.2.1"
11939
11939
  },
11940
11940
  "bin": {
@@ -1,12 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from 'node:child_process';
3
3
  import { createHash } from 'node:crypto';
4
- import { DatabaseSync } from 'node:sqlite';
5
4
  import { chmod, copyFile, lstat, mkdir, mkdtemp, readFile, readdir, readlink, rename, rm, symlink, writeFile } from 'node:fs/promises';
6
5
  import { existsSync } from 'node:fs';
7
6
  import { homedir, hostname, userInfo } from 'node:os';
8
7
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
- import { fileURLToPath, pathToFileURL } from 'node:url';
8
+ import { fileURLToPath } from 'node:url';
10
9
  import { ENTRY_NAMES, GENERATION_ID, MANIFEST_KEYS, MANIFEST_SCHEMA, PACKAGE_NAME, contained, isKnownPackageName, isSealed, publishedMarkerPath, runtimeHome, sortInventory, validateManifestShape } from '../bin/runtime-generation-manifest.mjs';
11
10
  import { patchPiTreeRootOrdering } from './patch-pi-tree-root-ordering.mjs';
12
11
  import { smokeValidate } from './runtime-smoke.mjs';
@@ -165,13 +164,6 @@ async function removeStage(root) {
165
164
  * currently serving generation selected. The daemon-side migration guard is a
166
165
  * second line of defense for generations installed by older installers. */
167
166
  async function assertCanvasSchemaCompatible(stage) {
168
- const migrationsUrl = pathToFileURL(join(stage, 'dist', 'core', 'canvas', 'migrations.js')).href;
169
- const candidate = await import(migrationsUrl);
170
- const supported = candidate.MIGRATIONS?.length;
171
- if (!Number.isSafeInteger(supported) || supported < 0) {
172
- throw new Error('candidate runtime does not expose a valid canvas migration version');
173
- }
174
-
175
167
  const root = process.env.CRTR_HOME || (process.platform === 'linux' ? '/' : join(homedir(), '.crouter'));
176
168
  const runtime = join(root, 'runtime');
177
169
  // A machine (runtime/machine.json, written by the import) runs no canvas database: its control plane is the cloud's, and the cluster
@@ -181,27 +173,6 @@ async function assertCanvasSchemaCompatible(stage) {
181
173
  await assertPostgresSchemaCompatible(stage, runtime);
182
174
  return;
183
175
  }
184
-
185
- // No Postgres cluster yet: the canvas is still the SQLite file the next daemon boot imports.
186
- const dbPath = join(runtime, 'canvas.db');
187
- try {
188
- await lstat(dbPath);
189
- } catch (error) {
190
- if (error?.code === 'ENOENT') return; // no live database yet
191
- throw error;
192
- }
193
- const db = new DatabaseSync(dbPath, { readOnly: true });
194
- try {
195
- const { user_version: current } = db.prepare('PRAGMA user_version').get();
196
- if (current > supported) {
197
- throw new Error(
198
- `refusing to select runtime with canvas schema ${supported}: ` +
199
- `the live database is already at version ${current}; install a descendant build instead`,
200
- );
201
- }
202
- } finally {
203
- db.close();
204
- }
205
176
  }
206
177
 
207
178
  /** Refuse a candidate whose version is below `canvas_meta.schema_min_reader` (absent: `schema_version`) in the live Postgres
@@ -1 +0,0 @@
1
- export declare const sysMigrateLeaf: import("../../core/command.js").LeafDef;
@@ -1 +0,0 @@
1
- var s=Object.defineProperty;var n=(o,e)=>s(o,"name",{value:e,configurable:!0});import{defineLeaf as i}from"../../core/command.js";import{general as d}from"../../core/errors.js";import{cliClient as l,rethrowAsCliError as u}from"../api-client.js";import{layoutNeedsMigration as m}from"../../core/layout.js";import{migrateLayout as h}from"../../core/layout-migrate/index.js";const g=i({name:"migrate",description:"migrate an old runtime layout offline, then import the legacy memory stores into the canvas",whenToUse:"when the daemon reports startup `blocked` by the canvas import, or after moving from a release that kept memory as markdown stores. Run --dry-run first to see the plan and what it resolves; a write run on an imported home does nothing.",help:{name:"sys migrate",summary:"move an old runtime layout offline, then plan or run the daemon-owned canvas import",guide:"A layout migration requires the daemon to be stopped, runs in this process, and stops after writing the layout version; start the daemon and run `crtr sys migrate` again. The daemon then plans the canvas import: every legacy store (the user store, each profile store, every repository `.crouter/memory` reached from a profile project or a node's cwd, node context folders and reports) becomes documents with their revision history, owned by the person, a profile, a repo, or a node. Both stages resolve leftovers and clashes themselves (a folder with no node row is set aside, two repos with one namespace get distinct handles, an unparseable file imports as its raw text, and so on) and list each in `layout_resolutions` and `resolutions`, on the dry run too. The daemon runs the import itself at startup; only a blocker (the store migrations of a skipped release never ran) makes it write nothing and hold startup in `blocked`. The import writes in one transaction and resumes startup. The markdown files are left on disk and are never read again.",params:[{kind:"flag",name:"dry-run",type:"bool",required:!1,constraint:"Plan and report without writing. On an imported home, returns the recorded report with pending false."}],output:[{name:"loose_keys",type:"string[]",required:!1,constraint:"Loose credential paths moved or set aside; never values."},{name:"layout_moved",type:"number",required:!1,constraint:"Old-layout paths moved or stored paths rewritten on this run; present when the layout migration ran."},{name:"layout_resolutions",type:"string[]",required:!1,constraint:"One line per leftover the layout migration resolved (or, under --dry-run, will resolve): set-aside folders, moved profile files, closed worktree rows, cleared transcript paths."},{name:"layout_absent_credentials",type:"string[]",required:!1,constraint:"Old credential files the layout migration looked for and did not find (or, under --dry-run, will not find); present when the layout migration ran. An absent file is legitimate when the old home never held that credential."},{name:"stores",type:"object[]",required:!1,constraint:"Every store root found: {root, owner, docs, skipped?}; skipped is duplicate-worktree for a second checkout of an imported repo."},{name:"counts",type:"object",required:!1,constraint:"Planned (or written) totals: documents.<kind>, documents.owner.<person|profile|repo|node>, revisions, documents.rewritten, owners, stores, profile-limits, and informational counts. Empty on a write run over an imported home."},{name:"rewrites",type:"object[]",required:!1,constraint:"Pointer rewrites in head bodies: {path, from, to}."},{name:"dropped_fields",type:"object[]",required:!1,constraint:"Frontmatter fields with no canvas equivalent: {path, field}."},{name:"skipped",type:"object[]",required:!1,constraint:"Files or roots not imported, with the reason: {path, reason}."},{name:"resolutions",type:"object[]",required:!1,constraint:"Clashes the import resolved itself: {kind, message, paths}; kind is invalid-source, invalid-history, name-clash, repo-handle, profile-handle, repo-identity, or delivery-limit."},{name:"blockers",type:"object[]",required:!1,constraint:"{kind, message, paths}; kind is marker (the store migrations of a skipped release never ran). A blocker makes the command fail with this whole report in `received`; nothing is written."},{name:"dryRun",type:"boolean",required:!0,constraint:"True when nothing was written."},{name:"pending",type:"boolean",required:!1,constraint:"True while this home has not been imported."},{name:"resumed",type:"boolean",required:!1,constraint:"True only when this run resumed a blocked daemon startup."},{name:"resume_error",type:"string",required:!1,constraint:"Present when the import succeeded but normal daemon startup then failed."}],outputKind:"object",effects:["With an old layout and no layout version, refuses while a daemon answers, moves the runtime records, sets aside leftovers under runtime/set-aside/, rewrites stored paths and writes the layout version last, then stops; the next run, with the daemon started, plans or runs the canvas import.","Without --dry-run and with no blockers: stores revision bodies, converts profile project memory caps into profile delivery limits, and writes owners, documents, revisions, links, and the authoring nodes' watches in one canvas transaction, recorded so it runs once.","Under --dry-run: read-only, writes nothing."]},run:n(async o=>{const e=o.dryRun===!0,t=m()?await h(e):null;if(e&&t!==null)return{layout_resolutions:t.resolutions,layout_absent_credentials:t.absentCredentials,dryRun:e,follow_up:"Preview only \u2014 re-run without --dry-run to migrate the layout; the canvas import is planned after it."};if(t!==null)return{layout_moved:t.moved,layout_resolutions:t.resolutions,layout_absent_credentials:t.absentCredentials,dryRun:e,follow_up:"Layout migrated. Start the daemon (in a container, `docker compose exec`), then run `crtr sys migrate --dry-run` against it to plan the canvas import."};let r;try{r=await l().migrateState({dry_run:e})}catch(a){u(a)}if(r.blockers.length>0)throw d(`canvas import blocked by ${r.blockers.length} finding(s) \u2014 nothing was written`,{received:r,next:"Do what received.blockers[].message says, then run `crtr sys migrate` again."});return{...r,follow_up:r.pending?"Preview only \u2014 re-run without --dry-run to import.":e?"Already imported \u2014 this is the recorded report.":void 0}},"run")});export{g as sysMigrateLeaf};
@@ -1,46 +0,0 @@
1
- import { DatabaseSync } from 'node:sqlite';
2
- import pg from 'pg';
3
- export declare const IMPORT_MARK_KEY = "imported_from_sqlite";
4
- /** Written by `crtr sys db export-sqlite`; the Postgres data is stale against the exported canvas.db from then on. */
5
- export declare const EXPORT_MARK_KEY = "exported_to_sqlite";
6
- /** Every canvas table, in dependency order (a table follows every table its foreign keys name). The import and the
7
- * rollback export both copy exactly this list. */
8
- export declare const TABLE_ORDER: readonly ["objects", "documents", "revisions", "revision_parents", "jobs", "identities", "custom_objects", "context_sessions", "peer_stubs", "object_kinds", "watches", "watch_subscriptions", "exposures", "rules", "edges", "unresolved_links", "nodes", "focuses", "canvas_meta", "runtime_state", "warm_pool", "sessions", "executions", "worktrees", "node_faults", "node_tokens", "node_outcome_deliveries", "deleted_isolated_nodes", "create_requests", "waits", "messages", "message_sequence", "message_causes", "deliveries", "structured_requests", "daemon_actions", "human_requests", "human_action_deliveries", "review_comments", "review_comment_events", "run_events", "idempotency_keys", "grants", "memory_reads", "app_users", "uploads", "upload_uses", "shares", "audit_rows", "provider_approvals", "crons", "cron_runs", "peer_outbox", "peer_locations", "peer_ingested", "peer_ingested_destinations"];
9
- /** Columns holding `objects.rowid` in SQLite and `objects.id` in Postgres. */
10
- export declare const OBJECT_COLUMNS: Record<string, readonly string[]>;
11
- /** `optional`: the column may be left out of an INSERT (nullable, or it has a default or is an identity). */
12
- export interface PgColumn {
13
- name: string;
14
- type: string;
15
- identity: boolean;
16
- optional: boolean;
17
- }
18
- export interface ImportTableStat {
19
- table: string;
20
- rows: number;
21
- ms: number;
22
- }
23
- export interface ImportResult {
24
- tables: ImportTableStat[];
25
- verifyMs: number;
26
- totalMs: number;
27
- /** Per `table.column`, the NUL characters replaced with U+FFFD so jsonb would accept the value. */
28
- nulReplaced: Record<string, number>;
29
- }
30
- type Log = (message: string) => void;
31
- export declare function quote(identifier: string): string;
32
- export declare function pgColumns(client: pg.Client): Promise<Map<string, PgColumn[]>>;
33
- /** Copy an already-migrated SQLite database into the connected Postgres database, in one transaction. */
34
- export declare function copySqliteToPostgres(sqlite: DatabaseSync, client: pg.Client, options?: {
35
- log?: Log;
36
- }): Promise<ImportResult>;
37
- /** canvas.db → canvas.db.imported, with its -wal/-shm. An existing .imported (an earlier import, then a rollback export) is set aside, never overwritten. */
38
- export declare function renameImportedDatabase(path?: string): void;
39
- /**
40
- * Daemon boot: import `canvas.db` into the database at `url` if there is one. Holds the on-disk migration lock for
41
- * the whole import so `manage.ts` does not reap a daemon mid-copy. Re-entry: with the mark present and canvas.db
42
- * still there (a crash between commit and rename) the rename is finished and nothing is copied.
43
- * Returns null when there was nothing to do.
44
- */
45
- export declare function importSqliteCanvasIfPresent(url: string, log?: Log): Promise<ImportResult | null>;
46
- export {};
@@ -1,19 +0,0 @@
1
- var X=Object.defineProperty;var p=(s,t)=>X(s,"name",{value:t,configurable:!0});import{DatabaseSync as z}from"node:sqlite";import{createHash as Z,randomBytes as ee}from"node:crypto";import{existsSync as L,mkdirSync as te,renameSync as H}from"node:fs";import{dirname as oe}from"node:path";import se from"pg";import{withExclusiveDirectoryLockAsync as re}from"../exclusive-lock.js";import{DAEMON_STARTUP_WINDOW_MS as ne}from"../../daemon/startup-policy.js";import{migrate as ae}from"./migrations.js";import{readLegacyPrivacy as ie}from"../graph/types.js";import{LEGACY_LOCAL_PERSON as ce}from"./legacy-person.js";import{REBUILD_ALL_TOTALS as ue}from"../ledger/totals.js";import{canvasDbPath as U,onDiskMigrationLockPath as de}from"./paths.js";import{canvasSearchPathOptions as pe}from"./schema-version.js";const k="imported_from_sqlite",B="exported_to_sqlite",M=1e4,N=["objects","documents","revisions","revision_parents","jobs","identities","custom_objects","context_sessions","peer_stubs","object_kinds","watches","watch_subscriptions","exposures","rules","edges","unresolved_links","nodes","focuses","canvas_meta","runtime_state","warm_pool","sessions","executions","worktrees","node_faults","node_tokens","node_outcome_deliveries","deleted_isolated_nodes","create_requests","waits","messages","message_sequence","message_causes","deliveries","structured_requests","daemon_actions","human_requests","human_action_deliveries","review_comments","review_comment_events","run_events","idempotency_keys","grants","memory_reads","app_users","uploads","upload_uses","shares","audit_rows","provider_approvals","crons","cron_runs","peer_outbox","peer_locations","peer_ingested","peer_ingested_destinations"],me=new Set(["sqlite_sequence","sqlite_stat1","sqlite_stat4","reviews","usage","grantee_usage","provider_receipts"]),Ee={objects:["owner"],documents:["object"],revisions:["document","author"],jobs:["object"],identities:["object"],custom_objects:["object"],context_sessions:["node"],peer_stubs:["object"],object_kinds:["owner"],watches:["watcher","object","link_app"],exposures:["node","object"],rules:["object","owner"],edges:["src","dst"],unresolved_links:["src"]},W=new Set(["daemon_owner","schema_version","schema_min_reader","ledger_migrated"]),fe={canvas_meta:"key",message_sequence:"id"};function G(){return ee(16).toString("hex")}p(G,"newId");function f(s){return`"${s.replace(/"/g,'""')}"`}p(f,"quote");function we(s){switch(s){case"bigint":return"bigint[]";case"double precision":return"float8[]";case"bytea":return"bytea[]";case"text":case"jsonb":return"text[]";default:throw new Error(`import: no array type for Postgres column type ${s}`)}}p(we,"arrayType");async function le(s){const t=await s.query(`SELECT c.relname AS tbl, a.attname AS col, format_type(a.atttypid, a.atttypmod) AS type, a.attidentity <> '' AS identity, (NOT a.attnotnull OR a.atthasdef OR a.attidentity <> '') AS optional
2
- FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid
3
- WHERE c.relnamespace = current_schema()::regnamespace AND c.relkind = 'r' AND a.attnum > 0 AND NOT a.attisdropped
4
- ORDER BY c.relname, a.attnum`),e=new Map;for(const a of t.rows){const n=e.get(a.tbl)??[];n.push({name:a.col,type:a.type,identity:a.identity,optional:a.optional}),e.set(a.tbl,n)}return e}p(le,"pgColumns");const _e="\uFFFD";function he(s){if(!s.includes("\\u0000"))return{text:s,replaced:0};let t;try{t=JSON.parse(s)}catch{return{text:s,replaced:0}}let e=0;const a=p(d=>{const i=d.split("\0");return e+=i.length-1,i.join(_e)},"clean"),n=p(d=>typeof d=="string"?a(d):Array.isArray(d)?d.map(n):d!==null&&typeof d=="object"?Object.fromEntries(Object.entries(d).map(([i,_])=>[a(i),n(_)])):d,"walk"),c=n(t);return e===0?{text:s,replaced:e}:{text:JSON.stringify(c),replaced:e}}p(he,"scrubNul");async function ye(s,t,e,a,n,c,d){for(let i=0;i<a.length;i++)for(const _ of e){const o=n[c.indexOf(_)][i];if(o!=null){await s.query("SAVEPOINT import_probe");try{await s.query("SELECT $1::jsonb",[o]),await s.query("RELEASE SAVEPOINT import_probe")}catch(u){return await s.query("ROLLBACK TO SAVEPOINT import_probe"),new Error(`import: ${t}.${_.name} at ${d(a[i])} is not a value jsonb accepts: ${u.message}`,{cause:u})}}}}p(ye,"describeJsonbFailure");function v(s,t,e,a,n){if(n==null)return null;const c=s.get(Number(n));if(c===void 0)throw new Error(`import: ${e}.${a} references ${t} rowid ${String(n)}, which does not exist`);return c}p(v,"lookup");async function $e(s,t,e,a,n,c){const d=s.prepare(`PRAGMA table_info(${f(e)})`).all(),i=new Set(d.map(r=>r.name)),_=p(r=>r==="seq"||r==="watch_id"||r==="subscription_id","minted"),o=a.filter(r=>i.has(r.name)||_(r.name)||!r.optional),w=!s.prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?").get(e).sql.toUpperCase().includes("WITHOUT ROWID"),$=new Set(Ee[e]??[]),y=[];for(const r of o)if(r.name==="seq"&&!i.has("seq")){if(!w)throw new Error(`import: ${e} needs seq from rowid but has none`);y.push("rowid AS seq")}else if(r.name==="watch_id"||r.name==="subscription_id")y.push("NULL AS "+f(r.name));else if(i.has(r.name))y.push(f(r.name));else throw new Error(`import: SQLite table ${e} has no column ${r.name}`);w&&y.push("rowid AS _rowid");const h=e==="canvas_meta"?` WHERE key NOT IN (${[...W].map(r=>`'${r}'`).join(",")})`:"",b=s.prepare(`SELECT ${y.join(", ")} FROM ${f(e)}${h}${w?" ORDER BY rowid":""}`),S=o.map(r=>f(r.name)),R=o.map((r,m)=>`$${m+1}::${we(r.type)}`),O=o.map((r,m)=>`c${m}`),A=o.map((r,m)=>r.type==="jsonb"?`c${m}::jsonb`:`c${m}`);let j=`INSERT INTO ${f(e)} (${S.join(", ")}) SELECT ${A.join(", ")} FROM unnest(${R.join(", ")}) AS u(${O.join(", ")})`;const C=fe[e];if(C!==void 0){const r=o.filter(m=>m.name!==C).map(m=>`${f(m.name)} = EXCLUDED.${f(m.name)}`);j+=` ON CONFLICT (${f(C)}) DO UPDATE SET ${r.join(", ")}`}const D=e==="objects",x=o.filter(r=>r.type==="jsonb"),I=w?"_rowid":o[0].name,J=p(r=>`${w?"rowid":I} ${String(r[I])}`,"key");let P=0,g=[];const F=p(async()=>{if(g.length===0)return;const r=o.map(()=>new Array(g.length));if(g.forEach((m,T)=>{o.forEach((E,Q)=>{let l=m[E.name];if(e==="objects"&&E.name==="privacy"?l=ie(l):E.name==="watch_id"||E.name==="subscription_id"?l=G():e==="revision_parents"&&(E.name==="child"||E.name==="parent")?l=v(n.revisions,"revision",e,E.name,l):e==="watch_subscriptions"&&E.name==="watch"?l=v(n.watches,"watch",e,E.name,l):$.has(E.name)&&(l=D?null:v(n.objects,"object",e,E.name,l)),E.type==="bytea"&&l instanceof Uint8Array&&!Buffer.isBuffer(l)&&(l=Buffer.from(l.buffer,l.byteOffset,l.byteLength)),E.type==="jsonb"&&typeof l=="string"){const q=he(l);q.replaced>0&&(l=q.text,c.set(`${e}.${E.name}`,(c.get(`${e}.${E.name}`)??0)+q.replaced))}r[Q][T]=l??null}),e==="watches"&&n.watches.set(Number(m._rowid),r[o.findIndex(E=>E.name==="watch_id")][T])}),x.length===0)await t.query(j,r);else{await t.query("SAVEPOINT import_batch");try{await t.query(j,r)}catch(m){throw await t.query("ROLLBACK TO SAVEPOINT import_batch"),await ye(t,e,x,g,r,o,J)??m}await t.query("RELEASE SAVEPOINT import_batch")}P+=g.length,g=[]},"flush");for(const r of b.iterate())e==="objects"&&n.objects.set(Number(r._rowid),r.id),e==="revisions"&&n.revisions.set(Number(r._rowid),r.rev_id),g.push(r),g.length>=M&&await F();if(await F(),D){const r=s.prepare("SELECT id, owner FROM objects WHERE owner IS NOT NULL").all();for(let m=0;m<r.length;m+=M){const T=r.slice(m,m+M);await t.query("UPDATE objects o SET owner = v.owner FROM unnest($1::text[], $2::text[]) AS v(id, owner) WHERE o.id = v.id",[T.map(E=>E.id),T.map(E=>v(n.objects,"object","objects","owner",E.owner))])}}return P}p($e,"copyTable");async function Se(s,t){for(const[e,a]of t)for(const n of a)n.identity&&await s.query(`SELECT setval(pg_get_serial_sequence($1, $2), COALESCE((SELECT max(${f(n.name)}) FROM ${f(e)}), 1), (SELECT max(${f(n.name)}) IS NOT NULL FROM ${f(e)}))`,[f(e),n.name])}p(Se,"advanceIdentities");function Y(s,t,e=""){return Number(s.prepare(`SELECT count(*) AS n FROM ${f(t)}${e}`).get().n)}p(Y,"sqliteCount");async function ge(s,t,e){const a=[];for(const o of N){if(o==="canvas_meta")continue;const u=Y(s,o),w=Number((await t.query(`SELECT count(*) AS n FROM ${f(o)}`)).rows[0].n);u!==w&&a.push(`${o}: SQLite ${u} rows, Postgres ${w}`)}for(const o of s.prepare(`SELECT key, value FROM canvas_meta WHERE key NOT IN (${[...W].map(u=>`'${u}'`).join(",")})`).all())(await t.query("SELECT value FROM canvas_meta WHERE key = $1",[o.key])).rows[0]?.value!==o.value&&a.push(`canvas_meta ${o.key}: value differs`);const n=p(o=>{const u=Z("sha256");for(const w of o)u.update(w).update(`
5
- `);return u.digest("hex")},"hash"),c=s.prepare("SELECT id FROM objects ORDER BY rowid").all().map(o=>o.id),d=(await t.query("SELECT id FROM objects ORDER BY seq")).rows.map(o=>o.id);n(c)!==n(d)&&a.push("objects: ids in insertion order differ");const i=s.prepare("SELECT o.id AS id, p.id AS owner FROM objects o JOIN objects p ON p.rowid = o.owner ORDER BY o.rowid").all(),_=(await t.query("SELECT id, owner FROM objects WHERE owner IS NOT NULL ORDER BY seq")).rows;n(i.map(o=>`${o.id}>${o.owner}`))!==n(_.map(o=>`${o.id}>${o.owner}`))&&a.push("objects: owner links differ");for(const[o,u]of[["run_events","body_json"],["messages","body_json"],["deliveries","last_failure_json"]]){const w=Number(s.prepare(`SELECT COALESCE(sum(length(CAST(${f(u)} AS TEXT))), 0) AS n FROM ${f(o)}`).get().n),$=e.get(o).find(b=>b.name===u).type,y=$==="jsonb"?`${f(u)}::text`:f(u);if($==="jsonb")continue;const h=Number((await t.query(`SELECT COALESCE(sum(length(${y})), 0)::bigint AS n FROM ${f(o)}`)).rows[0].n);w!==h&&a.push(`${o}.${u}: total length SQLite ${w}, Postgres ${h}`)}if(a.length>0)throw new Error(`SQLite \u2192 Postgres import verification failed (rolled back; canvas.db untouched):
6
- ${a.join(`
7
- `)}`)}p(ge,"verify");async function be(s,t){const e=s.prepare("SELECT grantee, month, payer, source, served_model, input_tokens, output_tokens, cached_tokens, usd_equivalent FROM usage").all();if(e.length===0)return 0;const n=(await t.query("SELECT value FROM canvas_meta WHERE key = 'person_id'")).rows[0]?.value??ce,c=p((o,u=String)=>e.map(w=>w[o]===null?null:u(w[o])),"column"),d=await t.query(`INSERT INTO charges (id, request, at, month, kind, what, units, usd, payer, funding, sub, grantee, provider)
8
- SELECT 'legacy:' || u.grantee || ':' || u.month || ':' || u.payer || ':' || u.source || ':' || u.served_model,
9
- NULL, u.month || '-01T00:00:00.000Z', u.month,
10
- CASE WHEN u.source = 'model' THEN 'model' ELSE 'tool' END,
11
- CASE WHEN u.source = 'model' THEN u.served_model ELSE substr(u.source, 10) END,
12
- CASE WHEN u.source = 'model' THEN jsonb_build_object('input', u.input_tokens, 'output', u.output_tokens, 'cache_read', u.cached_tokens, 'cache_write', 0) END,
13
- u.usd_equivalent,
14
- CASE WHEN u.payer = 'app' THEN u.grantee ELSE $1::text END,
15
- CASE WHEN u.payer = 'app' THEN 'endpoint' WHEN u.source = 'model' THEN 'legacy' ELSE 'bill' END,
16
- $1::text, u.grantee,
17
- CASE WHEN u.source = 'model' THEN NULL ELSE 'app:' || substr(u.source, 10) END
18
- FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::bigint[], $8::bigint[], $9::bigint[], $10::float8[])
19
- AS u(grantee, month, payer, source, served_model, input_tokens, output_tokens, cached_tokens, usd_equivalent)`,[n,c("grantee"),c("month"),c("payer"),c("source"),c("served_model"),c("input_tokens"),c("output_tokens"),c("cached_tokens"),c("usd_equivalent",Number)]);for(const o of ue)await t.query(o);const i=(await t.query("SELECT count(*)::int AS n, COALESCE(SUM(usd), 0)::float8 AS usd FROM charges WHERE id LIKE 'legacy:%'")).rows[0],_=e.reduce((o,u)=>o+Number(u.usd_equivalent??0),0);if(d.rowCount!==e.length||i.n!==e.length||Math.abs(i.usd-_)>1e-4)throw new Error(`import: the usage \u2192 charges copy does not match (${e.length} usage rows, ${d.rowCount} charges inserted, ${i.n} legacy charges; usd ${_} vs ${i.usd})`);return e.length}p(be,"importLegacyUsage");async function Re(s,t,e={}){const a=e.log??(()=>{}),n=Date.now(),c=await le(t),d=s.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map(h=>h.name),i=d.filter(h=>!me.has(h)&&!N.includes(h));if(i.length>0)throw new Error(`import: SQLite tables with no copy rule: ${i.join(", ")}`);const _=N.filter(h=>!c.has(h));if(_.length>0)throw new Error(`import: Postgres tables missing from the schema: ${_.join(", ")}`);const o=d.includes("reviews")?Y(s,"reviews"):0;if(o>0)throw new Error(`import: the legacy reviews table still holds ${o} rows after the SQLite migration chain`);const u={objects:new Map,revisions:new Map,watches:new Map},w=[],$=new Map;let y=0;await t.query("BEGIN");try{await t.query("ALTER TABLE nodes DISABLE TRIGGER USER"),await t.query("ALTER TABLE deliveries DISABLE TRIGGER USER");for(const S of N){const R=Date.now(),O=await $e(s,t,S,c.get(S),u,$),A=Date.now()-R;w.push({table:S,rows:O,ms:A}),a(`import ${S}: ${O} rows in ${A} ms`)}await t.query("ALTER TABLE nodes ENABLE TRIGGER USER"),await t.query("ALTER TABLE deliveries ENABLE TRIGGER USER"),await Se(t,c);const h=await be(s,t);h>0&&a(`import usage: ${h} rows into charges`);const b=Date.now();await ge(s,t,c),y=Date.now()-b,a(`import verify: ${y} ms`),await t.query("INSERT INTO canvas_meta (key, value) VALUES ($1, $2)",[k,JSON.stringify({at:new Date().toISOString(),rows:w.reduce((S,R)=>S+R.rows,0)})]),await t.query("COMMIT")}catch(h){throw await t.query("ROLLBACK").catch(()=>{}),h}return $.size>0&&a(`import: replaced NUL (\\u0000) with U+FFFD in jsonb values: ${[...$].map(([h,b])=>`${h} ${b}`).join(", ")}`),{tables:w,verifyMs:y,totalMs:Date.now()-n,nulReplaced:Object.fromEntries($)}}p(Re,"copySqliteToPostgres");const K=["","-wal","-shm"];function V(s=U()){if(L(`${s}.imported`)){const t=`${s}.imported.${Date.now()}`;for(const e of K)L(`${s}.imported${e}`)&&H(`${s}.imported${e}`,`${t}${e}`)}for(const t of K)L(`${s}${t}`)&&H(`${s}${t}`,`${s}.imported${t}`)}p(V,"renameImportedDatabase");async function Pe(s,t=()=>{}){const e=U();if(!L(e))return null;const a=de();return te(oe(a),{recursive:!0,mode:448}),re(a,async()=>{if(!L(e))return null;const n=new se.Client({connectionString:s,application_name:`crtr-import-${process.pid}`,options:pe()});await n.connect();try{const c=await n.query("SELECT key FROM canvas_meta WHERE key = ANY($1)",[[k,B]]),d=new Set(c.rows.map(o=>o.key));if(d.has(k)){if(d.has(B))throw new Error(`${e} was written by \`crtr sys db export-sqlite\` and the Postgres database predates it; importing would drop the exported writes. Stop the daemon and delete the Postgres cluster (runtime/pg/data) to import ${e} afresh, or move ${e} aside to keep using Postgres.`);return V(e),t(`import: finished the rename of ${e} (already imported)`),null}const i=new z(e);let _;try{i.exec("PRAGMA busy_timeout = 5000;"),i.exec("PRAGMA foreign_keys = ON;"),ae(i),_=await Re(i,n,{log:t})}finally{i.close()}return V(e),t(`import: ${_.tables.reduce((o,u)=>o+u.rows,0)} rows in ${_.totalMs} ms; canvas.db renamed to canvas.db.imported`),_}finally{await n.end().catch(()=>{})}},{timeoutMs:ne,timeoutError:p(()=>new Error(`timed out waiting for the canvas import lock: ${a}`),"timeoutError")})}p(Pe,"importSqliteCanvasIfPresent");export{B as EXPORT_MARK_KEY,k as IMPORT_MARK_KEY,Ee as OBJECT_COLUMNS,N as TABLE_ORDER,Re as copySqliteToPostgres,Pe as importSqliteCanvasIfPresent,le as pgColumns,f as quote,V as renameImportedDatabase};
@@ -1,16 +0,0 @@
1
- import { DatabaseSync } from 'node:sqlite';
2
- export declare const MIGRATIONS: ReadonlyArray<(db: DatabaseSync) => void>;
3
- /** Bring `db` up to the latest schema version. Reads `user_version`, runs each
4
- * pending migration in order, and bumps `user_version` after each so the work
5
- * is gated and idempotent: re-running is a no-op once `user_version` reaches
6
- * `MIGRATIONS.length`. Forward-only.
7
- *
8
- * ATOMIC AND RESTARTABLE: each step AND its `user_version` bump run inside one
9
- * `BEGIN IMMEDIATE`/`COMMIT` (SQLite journals `user_version` with the
10
- * transaction, so a rollback restores it too). An interrupted or failing step
11
- * therefore leaves the db exactly at the previous version with none of its
12
- * writes committed — a half-applied step can never wedge every later open. The
13
- * write lock also serializes concurrent openers; the version is re-read after
14
- * acquiring it so a step another process just applied is skipped rather than
15
- * re-run. */
16
- export declare function migrate(db: DatabaseSync): void;